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
|
|---|---|---|---|---|
749,520
| 749,538
|
How to write my own wrapper in C#?
|
In my other question, I've been trying to find someone who knows where to find free open source OCR library for C#. However, it seems there is only C++ library and obviously, C++ is not C#.
One of the responds suggested to write my own wrapper in C#. I have pretty much no idea how to do it, where to learn to do it, or what it actually is - except I believe it's calling C++ methods in dll by changed method calls, .. that's just assumption, indeed.
Please, help out one more newbie. Thank you
|
You can get a good start here:
Call Unmanaged Code. Part 1 - Simple DLLImport
|
749,632
| 749,642
|
Thoughtworks Cruise: Unit Testing?
|
I'm evaluating Cruise (NOTE! Not CruiseControl but Cruise (commercial)) for doing CI with an unmanaged MSVC++ 2008 project. I use GoogleTest framework for my unit test. I know that GTest can output its result as an JUnit XML or XML format. My question is, does Cruise support JUnit/XML format?
How would Cruise know whether or not my unit test fail?
More information from Thoughtworks here:
|
According to the documentation, yes it does support the JUnit xml format. See the bottom of the page. Second to last section called "Publishing tests"
http://studios.thoughtworks.com/cruise-continuous-integration/1.2/help/managing_artifacts_and_reports.html
|
749,757
| 749,842
|
C++ Class Serialization
|
I quite recently learned about the C++ classes friend keyword and the uses in serialization and now I need some help in getting it to work.
I have no problem serializing my class to a file, it's working great, however i'm having a hard time trying to read this file into a vector container. I'm sure I need a loop in my code that reads line by line, but since the class has different types I guess I can't use std::getline() and also maybe that approach wouldn't use the istream method i implemented?
A sample output file would be:
Person 1
2009
1
Person 2
2001
0
My code:
class SalesPeople {
friend ostream &operator<<(ostream &stream, SalesPeople salesppl);
friend istream &operator>>(istream &stream, SalesPeople &salesppl);
private:
string fullname;
int employeeID;
int startYear;
bool status;
};
ostream &operator<<(ostream &stream, SalesPeople salesppl)
{
stream << salesppl.fullname << endl;
stream << salesppl.startYear << endl;
stream << salesppl.status << endl;
stream << endl;
return stream;
}
istream &operator>>(istream &stream, SalesPeople &salesppl)
{
stream >> salesppl.fullname;
stream >> salesppl.startYear;
stream >> salesppl.status;
// not sure how to read that empty extra line here ?
return stream;
}
// need some help here trying to read the file into a vector<SalesPeople>
SalesPeople employee;
vector<SalesPeople> employees;
ifstream read("employees.dat", ios::in);
if (!read) {
cerr << "Unable to open input file.\n";
return 1;
}
// i am pretty sure i need a loop here and should go line by line
// to read all the records, however the class has different
// types and im not sure how to use the istream method here.
read >> employee;
employees.push_back(employee);
By the way, I know that the Boost library has a great serialization class, however I'm trying to learn how serialization would work using the STL library for now.
Thanks a lot in advance for any help that you can give me and for getting me in the right track!
|
It looks like you pretty much have all the code you need already! I copied your code and compiled it with some changes to read the SalesPeople in from a file in a loop. I will include the changes below, but since this is for your homework, you may just want to read and think about the following hints before looking at the code.
For reading the SalesPeople in a
loop, I would recommend that you take
a look at this FAQ. It has an
example of almost exactly what you
need. FAQ 15.4 will also help
you, I believe.
For your question on how to handle
the extra empty line when reading
from the file, check out this
link. You can very simply
extract whitespace this way.
As jfclavette suggested, I would
recommend looking into
std::getline for reading in the
SalesPerson's full name, since you
need everything on that line into one
string.
I have one question for you, though: what about the employeeID? I notice that it is being ignored in your sample code. Is that on purpose?
And now, if you still need help, you can check out the code I wrote to get this to work:
istream &operator>>(istream &stream, SalesPeople &salesppl)
{
//stream >> salesppl.fullname;
getline(stream, salesppl.fullname);
stream >> salesppl.startYear;
stream >> salesppl.status;
// not sure how to read that empty extra line here ?
stream >> ws;
return stream;
}
while(read >> employee)
{
// cout << employee; // to verify the input, uncomment this line
employees.push_back(employee);
}
Also, as jfclavette suggested, it may not be a bad idea to add some input validation (check the stream status after reading from it and verify that it is still good). Although I would recommend using the while() loop for the reasons stated in FAQ 15.5.
|
749,865
| 754,496
|
C++ mutable appropriate in this case?
|
I would like to ask if the use of mutable is appropriate here:
#include <iostream>
class Base
{
protected:
int x;
public:
virtual void NoMod() const
{
std::cout << x << std::endl;
}
void Draw() const
{
this->NoMod();
}
};
class Derive : public Base
{
private:
mutable int y;
public:
void NoMod() const
{
y = 5;
}
};
int main()
{
Derive derive;
// Test virtual with derive
derive.Draw();
return 0;
}
The Base class is a 3rd-party library. I'm extending it to provide my own NoMod(). The library original NoMod() is declared as a const.
My NoMod() differs from Base in the fact that it needs to modify its own member variable.
Thus, for my own NoMod() to compile and get called when Draw() is called, I had to
1) Implement Derive::NoMod() as a const
2) make my int y mutable.
Is this the best I can do?
|
As 'head geek' described, the answer to your question depends on how your data member is used.
I distinguish two types of data members in a class.
I use the common term 'attribute' to refer to data members
that are the logical state or 'value' of the object.
Typically attributes are rarely declared as mutable.
I have coined the protologism 'contribute' it denote
data members that are simply 'working memory/storage'
and that are somewhat divorced from the state of the object.
Contributes have no contextual relevance to the user of the object,
they exist in the class only to contribute to the maintenance
and efficient operation of the object.
Contributes are usually declared in the class as mutable and are always
private or protected.
For example let's say your object is a linked list,
so you have a pointer to the first item in the list.
I would consider this pointer a contribute because
it does not represent the data in the list.
Even if the list is sorted and the
pointer is set to the new first item in the list,
the user of the list object could care less how the
list is maintained. Only that the list data has
been modified or not and that the the list is sorted or not is
relevant to the user's perspective.
Even if you had a booean data member 'sorted' to quickly determine
if the list is in a sorted state, that too would be a contribute
because it is the list structure itself which imbues the sorted state,
the 'sorted' variable member is used simply to efficiently remember the state
without having to scan the list.
As another example, if you have a const method that searches the list.
Suppose you know that typically the search will return the
most recently previously searched for item,
you would keep a pointer in your class to such a item so your method
can first check if the last found item matches the search key before searching
the entire list (if the method does indeed need to search the list and finds
an item, the pointer would be updated).
This pointer I would consider to be a contribute because it
is only there to help speed up the search. Even though the
search updates the pointer contribute, the method is effectively
const because none of the items' data in the container are modified.
So, data members that are attributes are usually not declared mutable,
and data members that contribute to the functioning of an object will usually be mutable.
|
750,087
| 750,171
|
Structure for hierarchal Component storage
|
I've been batting this problem around in my head for a few days now and haven't come to any satisfactory conclusions so I figured I would ask the SO crew for their opinion. For a game that I'm working on I'm using a Component Object Model as described here and here. It's actually going fairly well but my current storage solution is turning out to be limiting (I can only request components by their class name or an arbitrary "family" name). What I would like is the ability to request a given type and iterate through all components of that type or any type derived from it.
In considering this I've first implemented a simple RTTI scheme that stores the base class type through the derived type in that order. This means that the RTTI for, say, a sprite would be: component::renderable::sprite. This allows me to compare types easily to see if type A is derived from type B simply by comparing the all elements of B: i.e. component::renderable::sprite is derived from component::renderable but not component::timer. Simple, effective, and already implemented.
What I want now is a way to store the components in a way that represents that hierarchy. The first thing that comes to mind is a tree using the types as nodes, like so:
component
/ \
timer renderable
/ / \
shotTimer sprite particle
At each node I would store a list of all components of that type. That way requesting the "component::renderable" node will give me access to all renderable components regardless of derived type. The rub is that I want to be able to access those components with an iterator, so that I could do something like this:
for_each(renderable.begin(), renderable.end(), renderFunc);
and have that iterate over the entire tree from renderable down. I have this pretty much working using a really ugly map/vector/tree node structure and an custom forward iterator that tracks a node stack of where I've been. All the while implementing, though, I felt that there must be a better, clearer way... I just can't think of one :(
So the question is: Am I over-complicating this needlessly? Is there some obvious simplification I'm missing, or pre-existing structure I should be using? Or is this just inheritly a complex problem and I'm probably doing just fine already?
Thanks for any input you have!
|
You should think about how often you need to do the following:
traverse the tree
add/remove elements from the tree
how many objects do you need to keep track of
Which is more frequent will help determine the optimum solution
Perhaps instead of make a complex tree, just have a list of all types and add a pointer to the object for each type it is derived from. Something like this:
map<string,set<componenet *>> myTypeList
Then for an object that is of type component::renderable::sprite
myTypeList["component"].insert(&object);
myTypeList["renderable"].insert(&object);
myTypeList["sprite"].insert(&object);
By registering each obejct in multiple lists, it then becomes easy to do something to all object of a given type and subtypes
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(),renderFunc);
Note that std::set and my std::map construct may not be the optimum choice, depending on how you will use it.
Or perhaps a hybrid approach storing only the class heirarchy in the tree
map<string, set<string> > myTypeList;
map<string, set<component *> myObjectList;
myTypeList["component"].insert("component");
myTypeList["component"].insert("renderable");
myTypeList["component"].insert("sprite");
myTypeList["renderable"].insert("renderable");
myTypeList["renderable"].insert("sprite");
myTypeList["sprite"].insert("sprite");
// this isn't quite right, but you get the idea
struct doForList {
UnaryFunction f;
doForList(UnaryFunction f): func(f) {};
operator ()(string typename) {
for_each(myTypeList[typename].begin();myTypeList[typename].end(), func);
}
}
for_each(myTypeList["renderable"].begin(),myTypeList["renderable"].end(), doForList(myFunc))
|
750,178
| 750,197
|
Is it a good idea to typedef pointers?
|
I looked through some code and noticed that the convention was to turn pointer types like
SomeStruct*
into
typedef SomeStruct* pSomeStruct;
Is there any merit to this?
|
This can be appropriate when the pointer itself can be regarded as a "black box", that is, a piece of data whose internal representation should be irrelevant to the code.
Essentially, if your code will never dereference the pointer, and you just pass it around API functions (sometimes by reference), then not only does the typedef reduce the number of *s in your code, but also suggests to the programmer that the pointer shouldn't really be meddled with.
This also makes it easier to change the API in the future if the need arises. For instance, if you change to using an ID rather than a pointer (or vice versa) existing code won't break because the pointer was never supposed to be dereferenced in the first place.
|
750,336
| 750,350
|
Is STL vector a better version of realloc?
|
In C++, I believe, a better way of dealing with reallocation is to use a STL vectors, as it guarantees the contiguous storage locations.
I have couple question to understand the difference:
Is there any scenario in which I need to prefer realloc over vector ?
Is there anything else ( apart from vector ) which is equivalent to realloc in C++?
Thanks,
|
It is only vector, which is guaranteed to have contiguous memory. Not the others.
realloc is a C memory management function. It's use is not encouraged in C++ code. Here's Stroustrup telling you why: Why doesn't C++ have an equivalent to realloc()?
However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array.
|
750,464
| 750,480
|
Comments in source code
|
How to keep the source code well documented/commented? Is there a tool to generate a skeleton for comments on the Unix platform for C++?
In general, how many lines of comments is recommended for a file with around 100 lines of code?
|
Generally, it's best to let the code itself explain what it does, whereas the comments are there to describe why it's like that. There is no number to stick to. If your 100 lines speak for themselves, don't comment at all or just provide a summary at the beginning. If there is some knowledge involved that's beyond what the code does, explain it in a comment.
If you're code is too complicated to explain itself, then that may be a reason to refactor.
This way, when you change the implementation you don't need to change the comments as well, as your comments do not duplicate the code. Since the reasons for the design seldom change it's safe to document them in comments for clarity.
|
750,635
| 750,662
|
dsn less connection using text driver
|
I am trying to do ODBC import with DSN-Less connection(using text driver). Is there any way to tell SQLDriverConnect to set COLNAMEHEADER=yes/no? OR I need to use schema.ini to do it?
Actually i don't want to create schema.ini manually, Can I use SQLConfigDataSource for dsn less connection? I haven't found any docs regarding this.
Thanks in advance,
Manoj
|
Create the schema.ini programatically before you open the text file via SQLDriverConnect. I don't see how SQLConfigDataSources can help you here, as it is specifically intended for manipulating DSNs and you don't have one.
|
750,941
| 750,973
|
double.Epsilon vs. std::numeric_limits<double>::min()
|
Why double.Epsilon != std::numeric_limits<double>::min()?
On my PC:
double.Epsilon == 4.9406564584124654E-324 and is defined in .NET
std::numeric_limits<double>::min() == 2.2250738585072014e-308
Is there a way to get 2.2250738585072014e-308 from .NET?
|
They're different because double.Epsilon returns the smallest representable value. numeric_limits<double>::min() returns the smallest normalized value.
Basically double.Epsilon is the equivalent to numeric_limits<double>::denorm_min().
The easiest way of getting the equivalent in .NET is probably to work out the bit pattern for the minimal normalized number and use BitConverter.Int64BitsToDouble.
|
751,100
| 751,111
|
Checking if a particular device driver is loaded
|
I'm trying to work out if I can check if a particular video card device driver is loaded in Windows Server 2003 using C++. Can anyone give me pointers on how I might achieve this?
Thanks
|
Use EnumDeviceDrivers - there's an example here.
|
751,119
| 751,147
|
Case Sensitive Partial Match with Boost's Regex
|
From the following code, I expect to get this output from the corresponding input:
Input: FOO Output: Match
Input: FOOBAR Output: Match
Input: BAR Output: No Match
Input: fOOBar Output: No Match
But why it gives "No Match" for input FOOBAR?
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string InputString = arg_vec[1];
string toMatch = "FOO";
const regex e(toMatch);
if (regex_match(InputString, e,match_partial)) {
cout << "Match" << endl;
} else {
cout << "No Match" << endl;
}
return 0;
}
Update:
Finally it works with the following approach:
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
bool testSearchBool(const boost::regex &ex, const string st) {
cout << "Searching " << st << endl;
string::const_iterator start, end;
start = st.begin();
end = st.end();
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
return boost::regex_search(start, end, what, ex, flags);
}
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string InputString = arg_vec[1];
string toMatch = "FOO*";
static const regex e(toMatch);
if ( testSearchBool(e,InputString) ) {
cout << "MATCH" << endl;
}
else {
cout << "NOMATCH" << endl;
}
return 0;
}
|
Your regular expression has to account for characters at the beginning and end of the sub-string "FOO".
I'm not sure but "FOO*" might do the trick
match_partial would only return true if the partial string was found at the end of the text input, not the beginning.
A partial match is one that matched
one or more characters at the end of
the text input, but did not match all
of the regular expression (although it
may have done so had more input been
available)
So FOOBAR matched with "FOO" would return false.
As the other answer suggests, using regex.search would allow you to search for sub-strings more effectively.
|
751,136
| 751,165
|
How do you pass a reference when using a typename as a function argument in C++?
|
I have some weird problem with templates. When trying to pass a parameterised iterator it complains that no function can be found. The code snippet is here, forget about the functionality, it's using the reference to the templatized iterator what interests me
#include <list>
#include <iostream>
template<typename T>
void print_list_element(typename std::list<T>::iterator& it){
std::cout << *it << std::endl;
}
int main() {
std::list<int> theList;
theList.push_back(1);
std::list<int>::iterator it = theList.begin();
print_list_element(it);
return 0;
}
If you try to compile this with g++ v4.3.2 it complains with a message saying that:
main.cpp:14: error: no matching function for call to 'print_list_element(std::_List_iterator<int>&)'
Is there something wrong with the code I wrote or is that g++ needs more information?
|
g++ can't figure out which template overload of print_list_element it should use. If you explicitly specify the template parameter it works:
print_list_element<int>(it);
|
751,840
| 752,458
|
How do I make textures transparent in OpenGL?
|
I've tried to research this on Google but there doesn't appear to me to be any coherent simple answers. Is this because it's not simple, or because I'm not using the correct keywords?
Nevertheless, this is the progress I've made so far.
Created 8 vertices to form 2 squares.
Created a texture with a 200 bit alpha value (so, about 80% transparent).
Assigned the same texture to each square, which shows correctly.
Noticed that when I use a texture with 255 alpha, it appears brighter.
The init is something like the following:
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, textureIds);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
int i, j;
GLubyte pixel;
for (i = 0; i < TEXTURE_HEIGHT; i++)
{
for (j = 0; j < TEXTURE_WIDTH; j++)
{
pixel = ((((i & 0x8) == 0) ^ ((j & 0x8) == 0)) * 255);
texture[i][j][0] = pixel;
texture[i][j][1] = pixel;
texture[i][j][2] = pixel;
texture[i][j][3] = 200;
}
}
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
TEXTURE_WIDTH, TEXTURE_HEIGHT,
0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
This is somewhat similar to the code snippet from page 417 in the book, OpenGL Programming Guide, and creates a check pattern.
And then, the display function contains...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
// Use model view so that rotation value is literal, not added.
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// ... translation, etc ...
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, +1.0, 0.0); // top left
glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0, 0.0); // bottom left
glTexCoord2f(1.0, 1.0); glVertex3f(+1.0, -1.0, 0.0); // bottom right
glTexCoord2f(1.0, 0.0); glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
// not neccecary to repeat, just good practice
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(-0.5, +1.0, -1.0); // top left
glTexCoord2f(0.0, 1.0); glVertex3f(-0.5, -1.0, -1.0); // bottom left
glTexCoord2f(1.0, 1.0); glVertex3f(+1.5, -1.0, -1.0); // bottom right
glTexCoord2f(1.0, 0.0); glVertex3f(+1.5, +1.0, -1.0); // top right
glEnd();
glFlush();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
SwapBuffers();
So, this renders a 2nd square in the background; I can see this but it looks like they're being blended with the background (I assume this because they are darker with 200 bit alpha than 255 bit) instead of the texture behind...
As you can see, no transparency... How can I fix this?
|
So the other answer which was here but was deleted mentioned this - Generally, for alpha blending to work correctly you need to sort the objects from far to near in the coordinate system of the camera.
This is why your polygons are blended with the background. You can confirm that this is indeed the problem by disabling the depth test. Without depth test all the fragments are displayed and you'll be able to see the alpha blending.
More on this in this page.
|
751,878
| 751,891
|
Determine array size in constructor initializer
|
In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?
class Class
{
public:
int array[];
Class(int x) : ??? { }
}
|
You can't initialize the size of an array with a non-const dimension that can't be calculated at compile time (at least not in current C++ standard, AFAIK).
I recommend using std::vector<int> instead of array. It provides array like syntax for most of the operations.
|
751,940
| 751,961
|
problem with containers: *** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***
|
I have a C++ program on Linux that crashes after some time with the message:
*** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***
Inside the program I make extensive use of containers. They have to store objects of a simple class.
EDIT 2009-4-17:
In the meantime it seems clear that the error has nothing to do with the simple class. The error still occurs if I change the containers to hold other datatypes. The problem must be somewhere else in my code, I'm trying to figure it out at the moment...
|
Consider using a std::string to hold the string value instead of a raw char pointer. Then you won't have to worry about managing the string data in your assignment, copy, and destruction methods. Most likely your problem lies there.
Edit: There's no issue with the newer class you posted, and no problem with the first version if you're only using the char * to point to string constants. The problem lies elsewhere in the program or with the way you're using the class. You'll have to spend more time digging in the debugger and/or valgrind to track down the problem. I would figure out what is pointed to at the specified address and try determine why it's being freed twice.
|
751,966
| 751,970
|
What are the negative consequences of including and/or linking things that aren't used by your binary?
|
Let's say that I have a binary that I am building, and I include a bunch of files that are never actually used, and do the subsequent linking to the libraries described by those include files? (again, these libraries are never used)
What are the negative consequences of this, beyond increased compile time?
|
A few I can think of are namespace pollution and binary size
|
751,994
| 752,024
|
C++ compression (zip) library for closed-source app
|
Please recommend a C++ compression (zip) library for a commercial, closed-source application. So, not a GPL license.
This is for my day job...
|
I know you said C++, but zlib is a very permissively licensed C library that you could use directly from a C++ app.
If I recall correctly, there are various "iostream-like" wrappers around zlib available, too.
|
752,006
| 752,098
|
What's the recommended way to get winhttp.h?
|
Our application uses libcurl for HTTP, and we want to get access to Internet Explorer's proxy settings. An earlier Stack Overflow question recommends that we use WinHttpGetIEProxyConfigForCurrentUser and WinHttpGetProxyForUrl.
Unfortunately, the winhttp.h header does not appear to be included with our copies either Visual C++ 2005 or Visual Studio 2008. Apparently, it's possible to download an updated Platform SDK and install it in Visual C++ 2005, but it's a pretty painful process, and it doesn't necessarily work with newer versions of Visual Studio.
Is there a good, well-supported way to access the WinHTTP 5.1 APIs from C++? Or should we avoid using these APIs?
|
The best, well-supported way to access the WinHTTP 5.1 APIs from C++ is via the Windows SDK (new name for the Platform SDK) and using those APIs you mentioned.
The article you linked to suggests that installing the SDK is difficult - the good news is its an old article from 2006 and things are much easier these days. Just do the following:
Download the latest SDK ISO image from here - don't worry about it being called the "SDK for Windows Server 2008", it's also for Server 2003, XP and Vista.
Burn to DVD
Run the setup.exe on the DVD, select full installation and let it run for 1/2 hour or so.
After installation, goto Start -> Programs -> Microsoft Windows SDK -> Visual Studio Registration -> Integrate Windows SDK with Visual Studio 2005
You may even be prompted to run the integration tool during installation - it's been a while since I installed it so I can't recall exactly.
The Visual C++ compiler will then be able to find winhttp.h and winhttp.lib in the appropriate folders.
Update As usual things are never as simple as they should be. EMK has pointed out that the Windows SDK Configuration Tool doesn't work properly with Visual Studio 2008 (any version) and crashes after installing Visual Studio 2008 SP1. Details and workarounds are reported here and here.
|
752,166
| 752,305
|
Splitting up a utility DLL into smaller components in C++
|
We have a core library in the form of a DLL that is used by more than one client application. It has gotten somewhat bloated and some applications need only a tiny fraction of the functionality that this DLL provides. So now we're looking at dividing this behemoth into smaller components.
My question is this: Can anyone recommend a path to take to divide this bloated DLL into a set of modules that have some interdepencies but do not necessarily require all other modules?
Here are the options as I see them but I'm hoping someone can offer other possibilities:
Create a "core" dll and several "satellite" dlls which use the core and possibly other satellite DLLs.
Subdivide the contents of the bloated DLL into static libraries that the main DLL uses (to maintain the same functionality) but apps that don't want to use the bloated version can assemble the static libraries they need into their own dll or into the app itself.
I was hesitant to mention this but I think it may be important to note that the app uses MFC.
Thanks for your thoughts.
|
Without having all the details it is a little hard to help but here is what I would do in your situation
provide both static and dll versions of whate3ver you release - for MT and single threaded.
try to glean from the disparate clients which items should be grouped together to provide reasonable segmentation - without having layers of dependencies.
having a "core" module sounds like a good idea - and make sure you don't have too many levels of dependencies - you might want to keep it simple.
You may find after the exercise that one big dll is actually reasonable.
Another consideration is that maintaining multiple DLLs and both static libs and DLLs will hugely increase the complexity of maintenance.
Are you going to be releasing them all at once every time, or are they going to be mix and match? Be careful here - and know that you could create testing issues
If no one is complaining about the size of the DLL then you might want to consider leaving it as is.
|
752,309
| 752,984
|
Ensuring C++ doubles are 64 bits
|
In my C++ program, I need to pull a 64 bit float from an external byte sequence. Is there some way to ensure, at compile-time, that doubles are 64 bits? Is there some other type I should use to store the data instead?
Edit: If you're reading this and actually looking for a way to ensure storage in the IEEE 754 format, have a look at Adam Rosenfield's answer below.
|
An improvement on the other answers (which assume a char is 8-bits, the standard does not guarantee this..). Would be like this:
char a[sizeof(double) * CHAR_BIT == 64];
or
BOOST_STATIC_ASSERT(sizeof(double) * CHAR_BIT == 64);
You can find CHAR_BIT defined in <limits.h> or <climits>.
|
752,479
| 752,498
|
Am I initializing my C++ reference variables correctly?
|
I've tried to Google this issue, and I can't find anything that I see as relevant. So I must be looking for the wrong thing; none the less, I'd appreciate some advice...
Foobar &foobar = *new Foobar(someArg, anotherArg);
Is it just me or does that seem smelly?
I understand that the new keyword is designed for use with pointers (as such):
Foobar *foobar = new Foobar(someArg, anotherArg);
But what if you don't require a pointer on that instance, and you would like to use a reference instead? Or, is it the case that you don't need to explicitly initialize it (much like local variables); and if this is the case, what if I want to initialize with parameters?
The following does not work (unless I'm doing something wrong):
// the last argument is of type: int
Foobar &foobar(someArg, anotherArg);
... gives the compiler error:
initializer expression list treated as compound expression
invalid initialization of non-const reference of type ‘Foobar&’
from a temporary of type ‘int’
And also this doesn't seem to work:
Foobar &foobar = Foobar(someArg, anotherArg);
... gives the compiler error:
error: invalid initialization of non-const reference of type
‘Foobar&’ from a temporary of type ‘Foobar’
Update 1:
Bare in mind that I am returning this value, so I don't want to use a local variable; I want to use a value on the heap, not the stack:
Foobar &helloWorld()
{
Foobar &foobar = *new Foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
Should I just be using pointers instead, or is this completely valid?
|
Why do you think you need to use new and references at all? Why not:
Foobar foobar(someArg, anotherArg);
For your function - return a value:
Foobar helloWorld()
{
Foobar foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
or a pointer:
Foobar * helloWorld()
{
Foobar * foobar = new Foobar(someArg, anotherArg);
foobar->HelloWorld();
return foobar;
}
If you do this - the caller is responsible for deleting the allocated object at some point.
Return from a non-member function is one place where references can typically not be used sensibly, as the thing you would like to refer to usually no longer exists.
|
752,492
| 763,478
|
Replying to a client over sockets (UDP) from a different process
|
I have a server than is a "command handler" process. It receives messages over UDP, and delegates the work to do to a different process by communicating to that process through it's published API (whatever IPC mechanism that process employes). Our system has several cooperating processes. The result of that API call is then then sent back to the client from the command handler process.
One command is to control a data stream that is generated from another process to the client (a "connect" message).
Should this work? I send the IP address and port number of the client to the other process, that process creates a new socket, and does a sendto...I've traced through the code and everything looks good, but the client is still blocked on the receive...I know if I do a sendto from the command handler, it gets the response, but not from the new socket.
Here's some example code:
#define LEN 10000
char buffer[LEN];
int sfd, nsfd, bread, addrsize;
struct sockaddr_in addr;
addrsize = sizeof (struct sockaddr_in);
server.sin_family = AF_INET;
server.sin_port = htons(5200);
server.sin_addr.s_addr = INADDR_ANY;
sfd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bind (sfd, (struct sockaddr*)&server, addrsize);
bread = recvfrom(sfd, buffer, LEN, 0, &addr, &addrsize);
/* send IP address and port number through the API to another process */
/* in that other process, I do something like this...addr has the IP
* address and port in it from above: */
nsfd = socket (AF_INET, SOCK_DGRAM, IPROTO_UDP);
sendto(nsfd, buff, bread, 0, &addr, sizeof(addr));
SO please help!
|
Your client (or a firewall in between) will likely get confused by receiving the response from a different source port than it sent the request to (as the OS will just pick a random source port for the new socket).
One way around this is to use the SO_REUSEADDR socket option in the server and explicitely bind to the correct port when sending the reply. But that would also have the undesireable side-effect that UDP requests might be redirected to one of the other processes instead of the server.
Another option (if you are using Unix/Linux) is to pass the server socket to the other processes via a unix domain socket (via sendmsg and ancillary data).
|
752,658
| 752,699
|
Is the practice of returning a C++ reference variable evil?
|
This is a little subjective I think; I'm not sure if the opinion will be unanimous (I've seen a lot of code snippets where references are returned).
According to a comment toward this question I just asked, regarding initializing references, returning a reference can be evil because, [as I understand] it makes it easier to miss deleting it, which can lead to memory leaks.
This worries me, as I have followed examples (unless I'm imagining things) and done this in a fair few places... Have I misunderstood? Is it evil? If so, just how evil?
I feel that because of my mixed bag of pointers and references, combined with the fact that I'm new to C++, and total confusion over what to use when, my applications must be memory leak hell...
Also, I understand that using smart/shared pointers is generally accepted as the best way to avoid memory leaks.
|
In general, returning a reference is perfectly normal and happens all the time.
If you mean:
int& getInt() {
int i;
return i; // DON'T DO THIS.
}
That is all sorts of evil. The stack-allocated i will go away and you are referring to nothing. This is also evil:
int& getInt() {
int* i = new int;
return *i; // DON'T DO THIS.
}
Because now the client has to eventually do the strange:
int& myInt = getInt(); // note the &, we cannot lose this reference!
delete &myInt; // must delete...totally weird and evil
int oops = getInt();
delete &oops; // undefined behavior, we're wrongly deleting a copy, not the original
Note that rvalue references are still just references, so all the evil applications remain the same.
If you want to allocate something that lives beyond the scope of the function, use a smart pointer (or in general, a container):
std::unique_ptr<int> getInt() {
return std::make_unique<int>(0);
}
And now the client stores a smart pointer:
std::unique_ptr<int> x = getInt();
References are also okay for accessing things where you know the lifetime is being kept open on a higher-level, e.g.:
struct immutableint {
immutableint(int i) : i_(i) {}
const int& get() const { return i_; }
private:
int i_;
};
Here we know it's okay to return a reference to i_ because whatever is calling us manages the lifetime of the class instance, so i_ will live at least that long.
And of course, there's nothing wrong with just:
int getInt() {
return 0;
}
If the lifetime should be left up to the caller, and you're just computing the value.
Summary: it's okay to return a reference if the lifetime of the object won't end after the call.
|
752,762
| 752,773
|
Is it good to have all the setter functions return a reference to the object in c++?
|
Is it good to have all the setter functions return a reference to the object in c++?
|
It's a usable enough pattern if there's a lot of things that need to be set on an object.
class Foo
{
int x, y, z;
public:
Foo &SetX(int x_) { x = x_; return *this; }
Foo &SetY(int y_) { y = y_; return *this; }
Foo &SetZ(int z_) { z = z_; return *this; }
};
int main()
{
Foo foo;
foo.SetX(1).SetY(2).SetZ(3);
}
This pattern replaces a constructor that takes three ints:
int main()
{
Foo foo(1, 2, 3); // Less self-explanatory than the above version.
}
It's useful if you have a number of values that don't always need to be set.
For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite.
Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not...
|
752,793
| 752,875
|
Should C++ eliminate header files?
|
Many languages, such as Java, C#, do not separate declaration from implementation. C# has a concept of partial class, but implementation and declaration still remain in the same file.
Why doesn't C++ have the same model? Is it more practical to have header files?
I am referring to current and upcoming versions of C++ standard.
|
I routinely flip between C# and C++, and the lack of header files in C# is one of my biggest pet peeves. I can look at a header file and learn all I need to know about a class - what it's member functions are called, their calling syntax, etc - without having to wade through pages of the code that implements the class.
And yes, I know about partial classes and #regions, but it's not the same. Partial classes actually make the problem worse, because a class definition is spread across several files. As far as #regions go, they never seem to be expanded in the manner I'd like for what I'm doing at the moment, so I have to spend time expanding those little plus's until I get the view right.
Perhaps if Visual Studio's intellisense worked better for C++, I wouldn't have a compelling reason to have to refer to .h files so often, but even in VS2008, C++'s intellisense can't touch C#'s
|
753,312
| 753,461
|
Returning Large Objects in Functions
|
Compare the following two pieces of code, the first using a reference to a large object, and the second has the large object as the return value. The emphasis on a "large object" refers to the fact that repeated copies of the object, unnecessarily, is wasted cycles.
Using a reference to a large object:
void getObjData( LargeObj& a )
{
a.reset() ;
a.fillWithData() ;
}
int main()
{
LargeObj a ;
getObjData( a ) ;
}
Using the large object as a return value:
LargeObj getObjData()
{
LargeObj a ;
a.fillWithData() ;
return a ;
}
int main()
{
LargeObj a = getObjData() ;
}
The first snippet of code does not require copying the large object.
In the second snippet, the object is created inside the function, and so in general, a copy is needed when returning the object. In this case, however, in main() the object is being declared. Will the compiler first create a default-constructed object, then copy the object returned by getObjData(), or will it be as efficient as the first snippet?
I think the second snippet is easier to read but I am afraid it is less efficient.
Edit: Typically, I am thinking of cases LargeObj to be generic container classes that, for the sake of argument, contains thousands of objects inside of them. For example,
typedef std::vector<HugeObj> LargeObj ;
so directly modifying/adding methods to LargeObj isn't a directly accessible solution.
|
The second approach is more idiomatic, and expressive. It is clear when reading the code that the function has no preconditions on the argument (it does not have an argument) and that it will actually create an object inside. The first approach is not so clear for the casual reader. The call implies that the object will be changed (pass by reference) but it is not so clear if there are any preconditions on the passed object.
About the copies. The code you posted is not using the assignment operator, but rather copy construction. The C++ defines the return value optimization that is implemented in all major compilers. If you are not sure you can run the following snippet in your compiler:
#include <iostream>
class X
{
public:
X() { std::cout << "X::X()" << std::endl; }
X( X const & ) { std::cout << "X::X( X const & )" << std::endl; }
X& operator=( X const & ) { std::cout << "X::operator=(X const &)" << std::endl; }
};
X f() {
X tmp;
return tmp;
}
int main() {
X x = f();
}
With g++ you will get a single line X::X(). The compiler reserves the space in the stack for the x object, then calls the function that constructs the tmp over x (in fact tmp is x. The operations inside f() are applied directly on x, being equivalent to your first code snippet (pass by reference).
If you were not using the copy constructor (had you written: X x; x = f();) then it would create both x and tmp and apply the assignment operator, yielding a three line output: X::X() / X::X() / X::operator=. So it could be a little less efficient in cases.
|
753,440
| 753,541
|
Should network packet payload data be aligned on proper boundries?
|
If you have the following class as a network packet payload:
class Payload
{
char field0;
int field1;
char field2;
int field3;
};
Does using a class like Payload leave the recipient of the data susceptible to alignment issues when receiving the data over a socket? I would think that the class would either need to be reordered or add padding to ensure alignment.
Either reorder:
class Payload
{
int field1;
int field3;
char field0;
char field2;
};
or add padding:
class Payload
{
char field0;
char pad[3];
int field1;
char field2;
char pad[3];
int field3;
};
If reordering doesn't make sense for some reason, I would think adding the padding would be preferred since it would avoid alignment issues even though it would increase the size of the class.
What is your experience with such alignment issues in network data?
|
You should look into Google protocol buffers, or Boost::serialize like another poster said.
If you want to roll your own, please do it right.
If you use types from stdint.h (ie: uint32_t, int8_t, etc.), and make sure every variable has "native alignment" (meaning its address is divisible evenly by its size (int8_ts are anywhere, uint16_ts are on even addresses, uint32_ts are on addresses divisble by 4), you won't have to worry about alignment or packing.
At a previous job we had all structures sent over our databus (ethernet or CANbus or byteflight or serial ports) defined in XML. There was a parser that would validate alignment on the variables within the structures (alerting you if someone wrote bad XML), and then generate header files for various platforms and languages to send and receive the structures. This worked really well for us, we never had to worry about hand-writing code to do message parsing or packing, and it was guaranteed that all platforms wouldn't have stupid little coding errors. Some of our datalink layers were pretty bandwidth constrained, so we implemented things like bitfields, with the parser generating the proper code for each platform. We also had enumerations, which was very nice (you'd be surprised how easy it is for a human to screw up coding bitfields on enumerations by hand).
Unless you need to worry about it running on 8051s and HC11s with C, or over data link layers that are very bandwidth constrained, you are not going to come up with something better than protocol buffers, you'll just spend a lot of time trying to be on par with them.
|
753,564
| 753,631
|
Templated namespaces and typedefs are illeagal -- workarounds?
|
I have a templated function fct that uses some complex data structure based on the template parameter. It also calls some helper functions (templated on the same type) that are in a separate helpers namespace and use the same complex data structure. Now it gets really ugly because we cannot make one typedef for the complex type that all functions can access:
namespace helpers {
template<class T>
void h1(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){
// ...
}
}
template<class T>
void fct(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){
// ...
helpers::h1(bar);
}
Now I want to make it prettier, by using one typedef that all functions can use.
A templated typedef would be nice, but it's not allowed:
template<class T>
typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar;
Another solution would be, I think, to wrap all these functions in a templated namespace, but that's not allowed in C++ either (I heard it will be in `C++0x' ...).
We have of course templated classes, but note that I don't really want the user to have to construct an object and call member functions on it. So the workaround I ended up using was to use a templated class where all member functions are static:
template<class T>
class All {
typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar;
static void fct(const Bar& bar){
// ...
h1(bar);
}
private:
static void h1(const Bar& bar){
// ...
}
};
My question is: It's probably a bit funny if large parts of my code are organized like that? After all it's a bit unusual to have many classes with just static member functions? Are there other solutions/workaround that make the "templated typedef" / "templated namespace" possible?
|
Are there other solutions/workaround that make the "templated typedef" / "templated namespace" possible?
GOTW #79: Template Typedef
The New C++ Typedef Templates (See Section 1: The Problem and Current Workarounds)
|
753,764
| 754,668
|
Problem clearing Listview Header image on Vista
|
I'm having a problem on Vista with the Listview control, in particular setting custom icons on the header. Normally under XP or any of the previous version of Windows, if I added an icon (in C++), I could do so with the following:
HeaderItem.mask = HDI_FORMAT | HDI_IMAGE;
Header_GetItem(HeaderHWND, Column, &HeaderItem);
TurnOn(HeaderItem.fmt, HDF_IMAGE);
HeaderItem.iImage = Image;
if (Header_SetItem(HeaderHWND, Column, &HeaderItem) == 0)
printf("Failed to set header [%d:%.8X]\n", GetLastError(), GetLastError());
and then to remove the image, on a particular column, I could use the same process but instead of turning on the HDF_IMAGE bit, you just turn it off.
On Vista, however, when I turn it off it doesn't seem to actually be accepting the change. So, for instance, when I start my fmt is:
0x4000 (or basically HDF_STRING)
I turn on the icon, and it becomes:
0x5800 (or basically HDF_STRING | HDF_IMAGE | HDF_BITMAP_ON_RIGHT)
I then turn it off again, but the result is:
0x4800 (or basically HDF_STRING | HDF_IMAGE)
I've checked, and I setting it to HDF_STRING only, but once HDF_IMAGE is set, it seems to be impossible to remove. Header_SetImage doesn't return any errors, so I'm at a loss as far as what to do. I've also tried removing the Imagelist from the control, but it still leaves the space as if there still was an image there.
At the end of the day I need to be able to add and remove icons from the header, and when they are removed I need all the header space available again (as they were before any were displayed. Any help would be greatly appreciated - thanks in advance!
|
If you read the documentation http://msdn.microsoft.com/en-us/library/bb775247(VS.85).aspx, if you indicate HDI_IMAGE in mask then iImage should be a valid index, you have to set it to I_IMAGENONE in order to remove it.
If you want to remve an image you have to do something like this:
HeaderItem.mask = HDI_FORMAT | HDI_IMAGE;
Header_GetItem(HeaderHWND, Column, &HeaderItem);
HeaderItem.fmt &= ~(HDF_IMAGE | HDF_BITMAP_ON_RIGHT);
HeaderItem.iImage = I_IMAGENONE;
Header_SetItem(HeaderHWND, Column, &HeaderItem);
|
754,065
| 795,722
|
Is there any way to prevent Boost.Build from recursively scanning header files for #include directives?
|
Is there a way to limit the header files that Boost.Build recursively scans for #include directives to a particular directory or set of directories? I.e. I'd like it to recursively scan the header files within my project only. I know that they external dependencies are not going to change (and being Boost and Qt they're pretty big). I end up with around 50,000 targets in the dependency tree which takes a while to process (resulting in a 1-2 minute build time even if no files have actually changed).
The only solution I've found so far is to take advantage of the INCLUDE environment variable (I'm using MSVC) - this means Boost.Build need not be informed of the include paths (I'm using the feature) and hence will not scan them. This seems a bit of a hack.
I feel like I must be missing something obvious because I haven't been able to find other people experiencing similar problems, even though I ran into this almost immediately. The closest I've come is here.
Judging from the debug output (bjam -d 3) it also scans most of the header files more than once... I don't know if this means that they are added as dependencies more than once, but certainly the cost of loading a file and scanning the entire contents must add up?
If I could tell it not to bother scanning a particular directory or set of directories in which I can guarantee the header files are not going to change, that would be perfect.
|
This question was also posted on the Boost mailing list and we got an answer to it here: http://lists.boost.org/boost-build/2009/04/21734.php.
So it seems so far that the answer is that, at least out of the box, Boost.Build doesn't have this feature, and the solution is to customise Boost.Build to your needs, which makes a certain amount of sense.
However, I am still curious as to why this is not a more common problem for people. I see that caching the dependencies would reduce the time, but surely if we scan all external libraries we end up with a huge dependency tree, much of it redundant? When I'm working on a project, I'm not going to change the third party libraries very often at all, it seems a shame to pay for dependency checking on them.
|
754,355
| 754,533
|
Cross-Platform Generic Text Processing in C/C++
|
What's the current best practice for handling generic text in a platform independent way?
For example, on Windows there are the "A" and "W" versions of APIs. Down at the C layer we have the "_tcs" functions (like _tcscpy) which map to either "wcscpy" or "strcpy". And in the STL I've frequently used something like:
typedef std::basic_string<TCHAR> tstring;
What issues if any arise from these sorts of patterns on other systems?
|
There is no support for a generic (variable-width) chararacter like TCHAR in standard C++. C++ does have wchar_t, but the encoding isn't guaranteed. C++1x will much improve things once we have char16_t and char32_t as well as UTF-{8,16,32} literals.
I personally am not a big fan of generic characters because they lead to some nasty problems (like conversion) and, what's more, if you are using a type (like TCHAR) that might ever have a maximum width of 8, you might as well code with char. If you really need that backwards-compatibility, just use UTF-8; it is specifically designed to be a strict superset of ASCII. You may have to use conversion APIs (especially on Windows, which for some bizarre reason is UTF-16), but at least it'll be consistent.
EDIT: To actually answer the original question, other platforms typically have no such construct. You will have to define your TCHAR on that platform, or else use a library that provides one (but as you should no doubt be able to guess, I'm not a big fan of that concept in libraries either).
|
754,729
| 754,754
|
Copy constructor initialization lists
|
I know that if you leave a member out of an initialization list in a no-arg constructor, the default constructor of that member will be called.
Do copy constructors likewise call the copy constructor of the members, or do they also call the default constructor?
class myClass {
private:
someClass a;
someOtherClass b;
public:
myClass() : a(DEFAULT_A) {} //implied is b()
myClass(const myClass& mc) : a(mc.a) {} //implied is b(mc.b)??? or is it b()?
}
|
Explicitly-defined copy constructors do not call copy constructors for the members.
When you enter the body of a constructor, every member of that class will be initialized. That is, once you get to { you are guaranteed that all your members have been initialized.
Unless specified, members are default-initialized in the order they appear in the class. (And if they can't be, the program is ill-formed.) So if you define your own copy constructor, it's now up to you to call any member copy constructors as desired.
Here is a small program you can copy-paste somewhere and mess around with:
#include <iostream>
class Foo {
public:
Foo() {
std::cout << "In Foo::Foo()" << std::endl;
}
Foo(const Foo& rhs) {
std::cout << "In Foo::Foo(const Foo&)" << std::endl;
}
};
class Bar {
public:
Bar() {
std::cout << "In Bar::Bar()" << std::endl;
}
Bar(const Bar& rhs) {
std::cout << "In Bar::Bar(const Bar&)" << std::endl;
}
};
class Baz {
public:
Foo foo;
Bar bar;
Baz() {
std::cout << "In Baz::Baz()" << std::endl;
}
Baz(const Baz& rhs) {
std::cout << "In Baz::Baz(const Baz&)" << std::endl;
}
};
int main() {
Baz baz1;
std::cout << "Copying..." << std::endl;
Baz baz2(baz1);
}
As-is, this prints:
In Foo::Foo()
In Bar::Bar()
In Baz::Baz()
Copying...
In Foo::Foo()
In Bar::Bar()
In Baz::Baz(const Baz&)
Note that it's default-initializing the members of Baz.
By commenting out the explicit copy constructor, like:
/*
Baz(const Baz& rhs) {
std::cout << "In Baz::Baz(const Baz&)" << std::endl;
}
*/
The output will become this:
In Foo::Foo()
In Bar::Bar()
In Baz::Baz()
Copying...
In Foo::Foo(const Foo&)
In Bar::Bar(const Bar&)
It calls the copy-constructor on both.
And if we reintroduce Baz's copy constructor and explicitly copy a single member:
Baz(const Baz& rhs) :
foo(rhs.foo)
{
std::cout << "In Baz::Baz(const Baz&)" << std::endl;
}
We get:
In Foo::Foo()
In Bar::Bar()
In Baz::Baz()
Copying...
In Foo::Foo(const Foo&)
In Bar::Bar()
In Baz::Baz(const Baz&)
As you can see, once you explicitly declare a copy-constructor you are responsible for the copying of all class members; it's your constructor now.
This applies for all constructors, including move constructors.
|
754,865
| 754,894
|
View Compiler Mangled Names in C++
|
How do I view the compiler-generated mangled names for overloaded functions in C++? I'm using VC9 but answers for other compilers are welcome too.
Edit: I find all the answers useful here. Accepting the one I liked best.
|
You could look in the map file. Assuming you have map file generation turned on.
|
755,028
| 755,055
|
Overloading a method on default arguments
|
Is it possible to overload a method on default parameters?
For example, if I have a method split() to split a string, but the string has two delimiters, say '_' and "delimit". Can I have two methods something like:
split(const char *str, char delim = ' ')
and
split(const char *str, const char* delim = "delimit");
Or, is there a better way of achieving this? Somehow, my brain isn't working now and am unable to think of any other solution.
Edit: The problem in detail:
I have a string with two delimiters, say for example, nativeProbableCause_Complete|Alarm|Text. I need to separate nativeProbableCause and Complete|Alarm|Text and then further, I need to separate Complete|Alarm|Text into individual words and join them back with space as a separator sometime later (for which I already have written a utility and isn't a big deal). It is only the separation of the delimited string that is troubling me.
|
How about implementing as 2 different methods like
split_with_default_delimiter_space
split_with_default_delimiter_delimit
Personally I'd prefer using something like this (more readable.. intent conveying) over the type of overloading that you mentioned... even if it was somehow possible for the compiler to do that.
|
755,164
| 755,964
|
COM API - could not pass "NULL" for a pointer argument
|
I have a COM API foo, the IDL looks like:
foo([in] unsigned long ulSize, [in, size_is(ulSize)] unsigned char* pData)
when I consume this function with foo(0,NULL);
I get an error - NULL argument passed. Is there a way to workaround this?
|
Don't use char* in COM APIs -- use BSTR instead. Then pass an empty string.
foo([in] unsigned long ulSize, [in] BSTR pData)
...
foo(1, _bstr_t(""));
|
755,196
| 755,206
|
Deleting a pointer to const (T const*)
|
I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer:
delete p;
This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to support this:
delete this;
Or is there some other reason?
|
It's to support:
// dynamically create object that cannot be changed
const Foo * f = new Foo;
// use const member functions here
// delete it
delete f;
But note that the problem is not limited to dynamically created objects:
{
const Foo f;
// use it
} // destructor called here
If destructors could not be called on const objects we could not use const objects at all.
|
755,347
| 755,354
|
Are const_iterators faster?
|
Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes the code when you use const_iterator.
Is this really correct? If yes, what really happens internally that makes const_iterator faster?.
EDIT: I wrote small test to check const_iterator vs iterator and found varying results:
For iterating 10,000 objects const_terator was taking a few milliseconds (around 16 ms) less. But not always. There were iterations in which both were equal.
|
If nothing else, a const_iterator reads better, since it tells anyone reading the code "I'm just iterating over this container, not messing with the objects contained".
That's a great big win, never mind any performance differences.
|
755,372
| 755,386
|
Spawned processes becoming defunct
|
I use posix_spawnp to spawn child processes from my main process.
int iRet = posix_spawnp(&iPID, zPath, NULL, NULL, argv, environ);
if (iRet != 0)
{
return false;
}
Sometimes, after a child process is spawned without errors, it suddenly becomes defunct. How could this occur?
I use a signal handler to reap child processes:
void SigCatcher(int n)
{
while(waitpid( -1, NULL, WNOHANG ) > 0);
}
and I manually call it whenever I kill a child process.
kill(oProcID, SIGKILL);
signal (SIGCHLD, SigCatcher);
Could this cause spawned children to go defunct (without me calling kill)?
|
This:
kill(oProcID, SIGKILL);
signal (SIGCHLD, SigCatcher);
looks like a race condition. You need to install the signal handler before killing the child process, otherwise you risk missing the signal.
|
755,575
| 757,530
|
Is there a way to group a set of soap methods logically in a "class" type entity?
|
For our large C++ based project we now have a method to automatically generate code to expose our code as SOAP methods. This works really well, and we are planning to start implementing an RIA based application using Adobe AIR / Flex based on the API's we have exposed.
The question I have is about organizing SOAP webservices. The code I have exposes individual method calls which in our C++ code belong to classes. Thus far I have named the exposed methods by prefixing them with the name of the class which they came from in C++. Ideally however, there would be a way to group methods logically within the SOAP service so that I wouldn't have to take this step and it would be possible to ask for the services in a particular group (AKA class) once you have bound to the SOAP services using the WSDL file in your target language.
I'd really like to be able to reproduce the class structure that lies behind the SOAP layer on the server side in our client applications. Right now, I can see that I could do this by using the method names to determine what class they belong to, but if I could separate them in a cleaner way I would prefer it.
Look forward to hearing what you SOAP gurus know about this matter.
|
I've spent the afternoon looking into this and it seems I have two options, both of which I have mocked up, and both of which work: I'm just unsure which is best now!
Separate the methods in different "services" grouped logically dependent on the class they came from. It is possible to include multiple SOAP "services" in the same WSDL file so they can still be discovered by clients by visiting only one URL.
Separate the methods into different "ports" on the same SOAP service.
I'm confused about which to use since according to the spec a port is "an abstract set of operations supported by one or more endpoints", whereas a service is "a collection of related endpoints". This suggests that the correct way to group together operations is by using ports.
|
755,726
| 755,757
|
error C2664: in c++?
|
for (int v = 0; v <= WordChosen.length();v++)
{
if(Letter == WordChosen[v])
{
WordChosenDuplicate.replace(v,1,Letter);
}
}
I get this error
"Error 4 error C2664:
'std::basic_string<_Elem,_Traits,_Ax>
&std::basic_string<_Elem,_Traits,_Ax>::replace(__w64
unsigned int,__w64 unsigned int,const
std::basic_string<_Elem,_Traits,_Ax>
&)' : cannot convert parameter 3 from
'char' to 'const
std::basic_string<_Elem,_Traits,_Ax>
&' c:\documents and settings\main\my
documents\uni\2nd
year\tp2\hangman\hangman\hangman.cpp 147
"
I only got the error after putting this line in
WordChosenDuplicate.replace(v,1,Letter);
|
Or
WordChosenDuplicate.replace(v,1,std::string(Letter, 1));
|
755,783
| 755,880
|
What's the use of .map files the linker produces?
|
What is the use of .map files VC++ linker produces when /MAP parameter or "Generate map file" project setting is used? When do I need them and how do I benefit from them?
|
A nice article on how to use map files for finding crashes.
http://www.codeproject.com/KB/debug/mapfile.aspx
Manually doing all this is very uninteresting.
I am not aware of any tools which can read map file and help in finding the crash location. If anybody knows please update us.
|
755,835
| 755,845
|
How to add element to C++ array?
|
I want to add an int into an array, but the problem is that I don't know what the index is now.
int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
That code works because I know what index I am assigning to, but what if I don't know the index...
In PHP, I can just do arr[]=22;, which will automatically add 22 to the next empty index of the array. But in C++ I can't do that, it gives me a compiler error. What do you guys suggest?
|
There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the std::vector.
You can use a vector in this way:
#include <vector>
std::vector< int > arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
|
756,109
| 756,188
|
How does delete deal with pointer constness?
|
I was reading this question Deleting a const pointer and wanted to know more about delete behavior. Now, as per my understanding:
delete expression works in two steps:
invoke destructor
then releases the memory (often with a call to free()) by calling operator delete.
operator delete accepts a void*. As part of a test program I overloaded operator delete and found that operator delete doesn't accept const pointer.
Since operator delete does not accept const pointer and delete internally calls operator delete, how does Deleting a const pointer work ?
Does delete uses const_cast internally?
|
const_cast doesn't really do anything – it's a way to suppress compiler moaning about const-ness of the object. delete keyword is a compiler construct, the compiler knows what to do in this case and doesn't care about const-ness of the pointer.
|
756,439
| 756,487
|
What are the drawbacks to compiling C++ projects with /clr:safe to enable unit testing?
|
I would like to introduce unit testing to our C++ product and wanted to investigate the pros and cons of trying to use the CLR-based unit tests. I've read that if you compile with the /clr:safe option, you can call your existing C++ code.
I'm strictly a .NET developer, so I'm at a loss for how this would affect our codebase. What should I know about before I try to introduce this to the C++ team?
|
It's not going to work, at all. The C++ code will not compile under /clr:safe; pretty much every line will give an error. /clr:safe gets you a language that basically shares no datatypes with C++.
|
756,549
| 756,553
|
Checking real variable type in polymorphism (C++)
|
Suppose we have a class A and class B and C inherit from it.
Then we create an array of references to A's, and fill it with B's and C's.
Now we decided that we want to eliminate all the C's. Is there a way to check what type each field of the array really holds without doing something redundant like a returnType() function?
Edit: fixed "array of A's" to "array of references to A's".
|
You can't create an array of As and fill it with Bs and Cs - they will be sliced down to
As. You can create a n array of pointers to A , wich you can populate with pointers to B and pointers to C.
To check the type of something in this situation - use dynamic cast:
// create B or C randomly
A * a = rand() % 2 ? new B : new C;
if ( dynamic_cast <B *> ( a ) ) {
// it's a B
}
else {
// it isn't (must be C in this case)
}
|
756,611
| 760,535
|
midl error 2025 when compiling idl file on win32 (midl doesn't like string<40>)
|
The idl files I have compile fine with linux tools, but when I try to compile using midl I get an error
error MIDL2025 : syntax error : expecting a declarator or * near "<"
the line is:
typedef string<40> somestring;
Is this non-standard idl, or am I missing something? Is there a switch for midl to allow this?
I wish I could set the bounty on this sooner...
|
My mistake. It is ACE/TAO specific. there is a tao_idl.exe idl compiler/processor. I will tag this question with ACE TAO
|
756,848
| 756,866
|
Do templated classes inherit the members of the classes passed to them? (Specificly std::vector)
|
I have a question regarding vectors:
If I have a std::vector<MyClass> will this vector "inherit" the MyClass member functions or not? If not, then would be the best way to handle individually the MyClass members inside a loop? Would I have to create a new class object on each iteration and assign the current vector iterator to it?
class MyClass
{
public:
void setMembers(std::string &string, int &num)
{
mystring = string;
number = num;
}
string printString() { return mystring; }
int printNumber() { return number; }
private:
std::string mystring;
int number;
};
MyClass test;
std::vector<MyClass> vector;
std::string string = "Test 1";
int a = 3;
test.setMembers(string,a);
vector.push_back(test);
for(unsigned int i = 0; i<vector.size(); i++) {
cout << "Vector #" << << endl;
// does vector inherit member functions here?
cout << "mystring is: " << vector.printString()<< endl;
cout << "number is : " << vector.printNumber() << endl;
}
Thanks a lot in advance for your help.
|
No, the instance std::vector doesn't inherit your member variables. However the objects in the vector do have those member which you can access via operator[].
for (size_t i = 0; i < vector.size(); i++) {
cout << "Vector #" << i << endl;
cout << "mystring is: " << vector[i].printString() << endl;
cout << "number is : " << vector[i].printNumber() << endl;
}
Notice we say vector[i] now, which returns a value of type MyClass which does have the member functions printString() and printNumber().
You should go re-read the chapter on inheritance.
|
756,906
| 756,912
|
Can you resize a C++ array after initialization?
|
I'm learning to program, and C++ is my first language. Don't bother using pointers to show me - I don't understand them yet, and won't bother until I have more free time to dedicate to this.
int mergeSort()
{
const int n = 9;
int originalarray[n] = {1, 3, 5, 7, 9, 2, 4, 6, 8};
const int halfelements = (sizeof(originalarray) / sizeof(int)) / 2;
int farray[halfelements];
int sarray[halfelements];
for (int i = 0; i < halfelements; i++) {
farray[i] = originalarray[i];
}
for (int i = halfelements, x = 0; i < (halfelements * 2); i++, x++) {
sarray[x] = originalarray[i];
}
I was assigned (I'm not taking classes - just learning with a few friends helping me out) a merge sort algorithm, with the algorithm explained but not the implementation. I want to rewrite this so it will work for both odd and even integers. I tried adding this code:
if ((n % 2) != 0) int farray[halfelements + 1];
So that I could use the same integer to iterate over both subsequent arrays. A sizeof(farray) is showing to be 16 bytes, or 4 integers. So it isn't resizing. What I want to know - is it possible to resize arrays after they initialized?
Edit: How would I implement a vector? I don't understand how to use iterators in a loop to iterate over and copy the values.
|
C++ arrays are fixed in size.
If you need a "resizable array", you'll want to use std::vector instead of an array.
|
756,984
| 757,046
|
What can be done in VC++ (native) that can't be done with VC#?
|
What can be done in VC++ (native) that can't be done with VC#?
From what I can tell the only thing worth using VC++ native for is when you need to manage memory yourself instead of the CLR garbage collector, which I haven't seen a purpose in doing either (but thats for another question to be asked later).
|
I'm not sure if you're talking about language features or applications. My answer though is for applications / components.
Really there are only 2 things you cannot do in C# that you can do in C++.
You cannot use C#, or any other .Net language, to write a component for a system that only accepts native components
You cannot use C#, or any other .Net language, to alter certain properties of a CCW for which the CLR does not allow customization
The most notable item here is Device Drivers. This is a framework that only accepts native components and there is no way to plug in a managed component.
For everything else it's possible to do the same thing in C# as it is in C++. There are just a lot of cases where you simply don't want to and a native solution is better. It's possible for instance to manage and manipulate memory in C# via unsafe code or IntPtr. It's just not nearly as easy and generally there's no reason.
|
757,059
| 757,266
|
Position of least significant bit that is set
|
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.
A trivial implementation is this:
unsigned GetLowestBitPos(unsigned value)
{
assert(value != 0); // handled separately
unsigned pos = 0;
while (!(value & 1))
{
value >>= 1;
++pos;
}
return pos;
}
Any ideas how to squeeze some cycles out of it?
(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)
[edit] Thanks everyone for the ideas! I've learnt a few other things, too. Cool!
|
Bit Twiddling Hacks offers an excellent collection of, er, bit twiddling hacks, with performance/optimisation discussion attached. My favourite solution for your problem (from that site) is «multiply and lookup»:
unsigned int v; // find the number of trailing zeros in 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];
Helpful references:
"Using de Bruijn Sequences to Index a 1 in a Computer Word" - Explanation about why the above code works.
"Board Representation > Bitboards > BitScan" - Detailed analysis of this problem, with a particular focus on chess programming
|
757,153
| 757,328
|
Concatenating C++ iterator ranges into a const vector member variable at construction time
|
I have a class X, which I provide a snippet of here:
class X {
public:
template <typename Iter>
X(Iter begin, Iter end) : mVec(begin, end) {}
private:
vector<Y> const mVec;
};
I now want to add a new concatenating constructor to this class, something like:
template <typename Iter1, typename Iter2>
X(Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2) : mVec(???) { ??? }
Such a constructor would catenate the two ranges [begin1, end1) and [begin2, end2) into mVec. The challenges are
1) I would like to preserve the const on mVec, so that it is considered constant throughout the other methods of X.
2) I would like to avoid unnecessary copies if at all possible. That is, one solution is to have a static method that constructs a non-const temporary to range 1, inserts range 2 and returns it, and then define the concatenating constructor to
template <typename Iter1, typename Iter2>
X(Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2)
: mVec(concatenate(begin1, end1, begin2, end2)) { }
but that copies all the values at least one extra time, I believe.
|
Nice problem. I would try to implement a particular iterator wrapper type that turns the two ranges into a single range. Something in the lines of:
// compacted syntax for brevity...
template <typename T1, typename T2>
struct concat_iterator
{
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename iterator_traits<T1>::value_type value_type;
typedef *value_type pointer;
typedef &value_type reference;
concat_iterator( T1 b1, T1 e1, T2 b2, T2 e2 )
: seq1( b1 ), seq1end( e1 ), seq2( b2 ), seq2end( e2 );
iterator& operator++() {
if ( seq1 != seq1end ) ++seq1;
else ++seq2;
return this;
}
reference operator*() {
if ( seq1 != seq1end ) return *seq1;
else return *seq2;
}
pointer operator->() {
if ( seq1 != seq1end ) return &(*seq1);
else return &(*seq2);
}
bool operator==( concat_iterator const & rhs ) {
return seq1==rhs.seq1 && seq1end==rhs.seq2
&& seq2==rhs.seq2 && seq2end==rhs.seq2end;
}
bool operator!=( contact_iterator const & rhs ) {
return !(*this == rhs);
}
private:
T1 seq1;
T1 seq1end;
T2 seq2;
T2 seq2end;
};
template <typename T1, typename T2>
concat_iterator<T1,T2> concat_begin( T1 b1, T1 e1, T2 b2, T2 e2 )
{
return concat_iterator<T1,T2>(b1,e1,b2,e2);
}
template <typename T1, typename T2>
concat_iterator<T1,T2> concat_end( T1 b1, T1 e1, T2 b2, T2 e2 )
{
return concat_iterator<T1,T2>(e1,e1,e2,e2);
}
Now you could use:
class X {
public:
template <typename Iter, typename Iter2>
X(Iter b1, Iter e1, Iter2 b2, Iter2 e2 )
: mVec( concat_begin(b1,e1,b2,e2), concat_end(b1,e1,b2,e2) )
{}
private:
vector<Y> const mVec;
};
or (I have just thought of it) you don't need to redeclare your constructor. Make your caller use the helper functions:
X x( concat_begin(b1,e1,b2,e2), concat_end(b1,e1,b2,e2) );
I have not checked the code, just typed it here off the top of my head. It could compile or it could not, it could work or not... but you can take this as a start point.
|
757,234
| 757,290
|
I'm concerned this code isn't doing what I want it to because of the way objects are used
|
I have the following code and I was wondering if someone could look at it for me.
I have a multi-threaded application that all share an object and operate on it. I've created a pointer to a certain element of it, just so I don't have to type in the long path every time, but I'm concerned it might simply be modifying a copy of the shared object, rather than the shared object itself.
Here is the code:
RPCThread* thr = &(args->s->_shared-_>rpcThread[args->threadIndex]);
...
thr->_in_use = true;
...
sema_post(&(thr->_sem_result));
Is this valid or would this just be modifying a copy?
|
Depends on the type of member _rpcThread. If it's simply RPCThread[] or *RPCThread
then I don't think you have a problem. If it's a class type then you need
to know the return type of its operator[]. If the relevant definition is
returning a value rather than a reference, you probably have a copy.
Unless, of course, RPCThread is a class that uses the envelope-letter idiom or implements a virtual Proxy.
If _rpcThread is just an array, you shouldn't have an aliasing issue here of the kind about which you're asking.
Here's a good thing to check without doing much more code reading. Can you change this:
RPCThread* thr = &(args->s->_shared->_rpcThread[args->threadIndex]);
to this:
RPCThread* thr = args->s->_shared->_rpcThread + args->threadIndex;
without causing a compile-time error?
|
757,241
| 757,254
|
In which order should classes be declared in C++?
|
Say I got this C++ code:
class class1{
class2 *x;
}
class class2{
class1 *x;
}
The compiler would give an error in line 2 because it couldn't find class2, and the same if i switched the order of the classes. How do I solve this?
|
Two things - one, you need semicolons after class declarations:
class class1{
class2 *x;
};
class class2{
class1 *x;
};
Two, you can create a declaration in front of the definitions of the classes. That tells the compiler that this class exists, and you have yet to define it. In this case, put a class2 declaration in front of the definition of class1:
class class2 ;
class class1{
class2 *x;
};
class class2{
class1 *x;
};
|
757,270
| 757,385
|
Is making a function template specialization virtual legal?
|
In C++, a function template specialization is supposed to act exactly like a normal function. Does that mean that I can make one virtual?
For example:
struct A
{
template <class T> void f();
template <> virtual void f<int>() {}
};
struct B : A
{
template <class T> void f();
template <> virtual void f<int>() {}
};
int main(int argc, char* argv[])
{
B b;
A& a = b;
a.f<int>();
}
Visual Studio 2005 gives me the following error:
fatal error C1001: An internal error has occurred in the compiler.
|
Nice compiler error. For this type of checks I always fallback to the Comeau compiler before going back to the standard and checking.
Comeau C/C++ 4.3.10.1 (Oct 6 2008
11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing.
All rights reserved. MODE:strict
errors C++ C++0x_extensions
"ComeauTest.c", line 3: error:
"virtual" is not allowed in a function
template
declaration
template virtual void f();
^
"ComeauTest.c", line 10: error:
"virtual" is not allowed in a function
template
declaration
template virtual void f();
^
Now, as it has been posted by another user, the fact is that the standard does not allow you to define virtual templated methods. The rationale is that for all virtual methods, an entry must be reserved in the vtable. The problem is that template methods will only be defined when they have been instantiated (used). This means that the vtable would end up having a different number of elements in each compilation unit, depending on how many different calls to f() with different types happen. Then hell would be raised...
If what you want is a templated function on one of its arguments and one specific version being virtual (note the part of the argument) you can do it:
class Base
{
public:
template <typename T> void f( T a ) {}
virtual void f( int a ) { std::cout << "base" << std::endl; }
};
class Derived : public Base
{
public:
virtual void f( int a ) { std::cout << "derived" << std::endl; }
};
int main()
{
Derived d;
Base& b = d;
b.f( 5 ); // The compiler will prefer the non-templated method and print "derived"
}
If you want this generalized for any type, then you are out of luck. Consider another type of delegation instead of polymorphism (aggregation + delegation could be a solution). More information on the problem at hand would help in determining a solution.
|
757,298
| 757,431
|
Loading Managed C++ DLL from plain C++ Program via LoadLibrary
|
I'm trying to get a simple mixture between Managed C++ and plain C++ working. I'm using Visual Studio 2005 but keep hitting a problem. Here's my setup.
First, I have a simple DLL built from the code
#using "mscorlib.dll"
#include "windows.h"
__declspec(dllexport)
void sayHello()
{
OutputDebugStringA( "Hello from managed code!" );
}
I compile this on the commandline to a DLL using
cl /CLR /LD dllcode.cpp
Next, I have a simple program consisting of nothing more than
#include <windows.h>
int main()
{
HINSTANCE lib = LoadLibrary( "dllcode.dll" );
if ( !lib ) {
return 1;
}
return 0;
}
I build an application out of this using
cl loader.cpp
So I end up with dllcode.dll and loader.exe in the same directory. When trying to run loader.exe, I always get return code '1'. Looking up the error code yielded by GetLastError() shows that loading dllcode.dll failed due to The specified module could not be found.
Does anybody know why this could be? Does it have something to do with manifests which need to be embedded into dllcode.dll or so? I ran the depends program on dllcode.dll but it didn't yield any problems as far as I could tell.
|
I just found out why loading the Managed C++ DLL from my vanilla C++ program didn't work. Thanks once again to jdigital for pointing me to a useful tool:
The source of the error was that the MSVC8 runtime library was not found. I thought that the manifest which is generated when building via
cl /CLR /LD dllcode.cpp
is already embedded into the DLL. Apparently, it's not - so the loader failed to locate the appropriate MSVCR80.dll copy.
I fixed this problem by adding a second step to the DLL building routine:
cl /CLR /LD dllcode.cpp
mt -manifest dllcode.dll.manifest -outputresource:dllcode.dll;2
Hope this helps. Quite a beginner problem, I suspect...
|
757,418
| 757,537
|
Should I compile with /MD or /MT?
|
In Visual Studio, there's the compile flags /MD and /MT which let you choose which kind of C runtime library you want.
I understand the difference in implementation, but I'm still not sure which one to use. What are the pros/cons?
One advantage to /MD that I've heard, is that this allows someone to update the runtime, (like maybe patch a security problem) and my app will benefit from this update. Although to me, this almost seems like a non-feature: I don't want people changing my runtime without allowing me to test against the new version!
Some things I am curious about:
How would this affect build times? (presumably /MT is a little slower?)
What are the other implications?
Which one do most people use?
|
By dynamically linking with /MD,
you are exposed to system updates (for good or ill),
your executable can be smaller (since it doesn't have the library embedded in it), and
I believe that at very least the code segment of a DLL is shared amongst all processes that are actively using it (reducing the total amount of RAM consumed).
I've also found that in practice, when working with statically-linked 3rd-party binary-only libraries that have been built with different runtime options, /MT in the main application tends to cause conflicts much more often than /MD (because you'll run into trouble if the C runtime is statically-linked multiple times, especially if they are different versions).
|
757,465
| 757,490
|
Why doesn't auto_ptr construction work using = syntax
|
I ran into a compiler error that didn't make much sense to me:
#include <memory>
using namespace std;
auto_ptr<Table> table = db->query("select * from t");
error: conversion from 'Table*' to non-scalar type 'std::auto_ptr< Table>' requested
However, the following line does work:
auto_ptr<Table> table(db->query("select * from t"));
What is it about this definiton of the constructor that prevents it from working as I expect? I thought that initialized declarations used the constructors.
Here's my auto_ptr's constructor (from the SGI STL):
explicit
auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { }
|
It's the "explicit" keyword.
template <typename T>
struct foo
{
explicit foo(T const *)
{
}
};
template <typename T>
struct bar
{
bar(T const *)
{
}
};
int main(int argc, char **argv)
{
int a;
foo<int> f = &a; // doesn't work
bar<int> b = &a; // works
}
The "explicit" keyword prevents the constructor from being used for implicit type conversions. Consider the following two function prototypes:
void baz(foo<int> const &);
void quux(bar<int> const &);
With those definitions, try calling both functions with an int pointer:
baz(&a); // fails
quux(&a); // succeeds
In the case of quux, your int pointer was implicitly converted to a bar.
EDIT: To expand on what other people commented, consider the following (rather silly) code:
void bar(std::auto_ptr<int>);
int main(int argc, char **argv)
{
bar(new int()); // probably what you want.
int a;
bar(&a); // ouch. auto_ptr would try to delete a at the end of the
// parameter's scope
int * b = new int();
bar(b);
*b = 42; // more subtle version of the above.
}
|
757,556
| 758,215
|
Determine if device is connected/disconnected to RS232 port without opening the port
|
I"m working on a C++ Win32 application for which I'm trying to essentially "auto detect" if a device has been plugged into one of the RS232 ports and then if it has been disconnected.
The checking for a connected device is easy enough because my use case allows me to assume that this particular thread will be the first to try to initiate communication with the port. I'm able to scan the available ports every minute or so and once I've found a port with the device on it I flag that port has having a device, close the port, then set an event so that the process that actually will use the device knows it can now connect on that port.
The disconnect detect is where I run into trouble. When I'm scanning for connected devices I can actually send data to the port to be sure that, if there is a device, it's the specific device I'm looking for. But once it's connected, that port will already be open by the other process and I can no longer open that port from the detect thread. So I am looking for a way to either open the port in a "listen mode" or something like that so I can just see if the device is still there.
I briefly came across something about watching the DSR or DTR line or something...but couldn't find any more or how to actually do it.
Any suggestions?
Edit: Looks like I need to clarify a little more... For detecting the disconnect, I cannot send data to the RS232 port in any way. Also, I cannot assume that another application actually has the port open. The device may be physically connected, but without and open connection...but I still can't risk sending data to it. I was hoping there was a way to just check that there was still power on that port or something like that.
|
It depends on the connected hardware whether there will be a change in the modem state registers when you disconnect the hardware, but if there is then you could check the state of for example the CTS or DSR line using the GetCommModemStatus() function.
There is however the problem that you need a file handle to the COM port to call any API function, and this is exclusive as the documentation of CreateFile() states:
The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, the dwShareMode parameter must be zero (exclusive access)
So you can not open the COM port to watch the line state while another process has the port opened for communication.
There are ways to do this, but they involve a driver. SysInternals has the Portmon tool, and a Google search will turn up some companies selling software for sharing COM port access between applications, but AFAIK simultaneous access is impossible using the standard API.
|
757,698
| 757,715
|
Increment/decrement versus assignment?
|
I'm recording some statistics in my application. One of the statistics is the size of BigDataStructure. I have two options:
Create a counter and increment /
decrement the counter each time
there is an add/remove from the
BigDataStructure.
Each time there is an add/remove
from the BigDataStructure, set the
counter to BigDataStructure.size().
Is there a good argument for doing it one way or another? Incrementing / decrementing the counter myself avoids a call to BigDataStructure.size(). It also doesn't directly involve the assignment operator (although maybe it does under the hood?)
Given these two options, which one is preferable?
|
.size() would probably be the less error prone of the 2 options because it is idempotent. If you want to get into threading/synchronization issues, .size() is safer here.
Also, today you have only 1 place that adds entries, and 1 place that removes entries. But maybe in the future that won't be the case.
|
757,913
| 758,003
|
Black and White graphics context
|
I'm working in Quartz/Core-graphics. I'm trying to create a black and white, 1b per pixel graphics context.
I currently have a CGImageRef with a grayscale image (which is really black and white). I want to draw it into a black and white BitmapContext so I can get the bitmap out and compress it with CCITT-group 4. (For some reason Quartz won't let you save in any TIFF format other than LZW).
So, I need the 1bit per pixel data. I figure that drawing into a 1bpp context would do that. However, it won't let me create the context with:
context = CGBitmapContextCreate (data,
pixelsWide,
pixelsHigh,
1,
pixelsWide/8,
CGColorSpaceCreateDeviceGray(),
kCGImageAlphaNone
);
Is there a colorspace smaller than gray?
|
Even if 1-bit bitmaps were supported, if pixelsWide is not a multiple of 8, then the number of bytes per row is not an integer: for example, if your image is 12 pixels wide, then the number of bytes per row is one and a half. Your division expression will truncate this to one byte per row, which is wrong.
But that's if 1-bit bitmaps were supported, which they aren't.
|
757,933
| 757,978
|
How do you change the filename extension stored in a string in C++?
|
Alright here's the deal, I'm taking an intro to C++ class at my university and am having trouble figuring out how to change the extension of a file. First, what we are suppose to do is read in a .txt file and count words, sentences, vowels etc. Well I got this but the next step is what's troubling me. We are then suppose to create a new file using the same file name as the input file but with the extension .code instead of .txt (in that new file we are then to encode the string by adding random numbers to the ASCII code of each character if you were interested). Being a beginner in programming, I'm not quite sure how to do this. I'm using the following piece of code to at first get the input file:
cout << "Enter filename: ";
cin >> filename;
infile.open(filename.c_str());
I'm assuming to create a new file I'm going to be using something like:
outfile.open("test.code");
But I won't know what the file name is until the user enters it so I can't say "test.txt". So if anyone knows how to change that extenstion when I create a new file I would very much appreciate it!
|
There are several approaches to this.
You can take the super lazy approach, and have them enter in just the file name, and not the .txt extension. In which case you can append .txt to it to open the input file.
infile.open(filename + ".txt");
Then you just call
outfile.open(filename + ".code");
The next approach would be to take the entire filename including extension, and just append .code to it so you'd have test.txt.code.
It's a bit ambiguous if this is acceptable or not.
Finally, you can use std::string methods find, and replace to get the filename with no extension, and use that.
|
758,014
| 758,053
|
Value of a variable using WinDbg
|
Question:
How to display the value of a C++ iterator using WinDbg, illustrated below:
for (vector<string>::iterator i = args.begin(); i != args.end(); i++)
//omitted
//for instance:
} else if (*i == "-i") {//attempting to display the value of *i
++i;
if (!::PathFileExistsA(i->c_str()))
{
Note:
Using ?? evaluate C++ expression command, which displays the following:
0:000> ?? i
class std::_Vector_iterator<std::basic_string<char,
std::char_traits<char>,
std::allocator<char> >,
std::allocator<std::basic_string<char,
std::char_traits<char>,
std::allocator<char> > > >
+0x000 _Mycont : 0x0012ff40 std::_Container_base_secure
+0x004 _Mynextiter : (null)
+0x008 _Myptr : 0x009c6198
std::basic_string<char,std::char_traits<char>,std::allocator<char> >
Can another command display/print the value of *i - please correct me if I'm wrong
|
Try:
dt -r i
Which will recursively dump the iterator. One of the members should be the info you seek. Verbose, but effective.
|
758,017
| 758,113
|
VC++ compiler and type conversion?
|
When I moved a program from a Mac to this Windows PC, the VC++ 2008 compiler is giving me errors for passing unsigned ints to the cmath pow() function. As I understand, this function is not overloaded to accept anything but floating-point numbers.
Is there some compiler flag/setting that will ignore these errors? Also does anyone know how to find the documentation on the VC++ compiler?
Edit
This isn't a warning, it's an error. However, for me it's not an issue since my program is only dealing with numbers that come out as integers, so I don't care that they aren't floats. If it was just warnings I would move on with my life, but it's not letting me compile. Can I suppress errors somehow? Like I said, the errors aren't coming up on my Mac and the program is fine.
|
Regarding other answers here, it is not a good idea to tell the question author to turn off this warning. His code is broken - he's passing an unsigned int instead of a float. You should be telling him to fix his code!
This isn't a warning, it's an error. However, for me it's not an issue since my
program is only dealing with numbers that come out as integers, so I don't care that
they aren't floats. If it was just warnings I would move on with my life, but it's not
letting me compile. Can I suppress errors somehow? Like I said, the errors aren't
coming up on my Mac and the program is fine.
Integers and floats use different representations internally. If you have the same number in an int and a float, the bit pattern inside the storage for them is completely different. You cannot under any circumstances whatsoever expect your code to work if you are passing an integer when you should be passing a float.
Furthermore, I assert your Mac code either is silently using an overloaded version of that function (e.g. you are on that platform compiling with C++) or you believe it works when in fact it is working by chance or is not actually working.
Addendum
No compilers ever written has the ability to turn off errors.
A warning means the compiler thinks you're making a mistake.
An error means the compiler doesn't know what to do.
|
758,023
| 758,448
|
What is the preferred method for creating a wxWidget application: using a GUI tool or procedurally in code?
|
I use wxWidgets to create test tools at work. I have always created the GUI by creating the widgets in code. I haven't tried any of the tools available that help to do this. How do other users of wxWidgets typically create their interface? If you use a tool, which tool do you use? If you use a tool, what advantages and disadvantages do you think there are for using that tool?
|
I've used wxFormBuilder for two reasons:
It's cross-platform and I needed something that would work on Linux.
I'm new to wxWidgets and I didn't want to spend lots of time futzing about with building the GUI.
I think it works quite well, and being familiar with similar GUI building tools (Borland C++ Builder, Jigloo for Java, Delphi) I found it easy to use.
If you stick with the paradigm of using wxFormBuilder to generate base classes, and then you make a class that inherits to layer your application specific logic on top, absolutely not hand-editing the C++ code wxFormBuilder generates, then it works well and you can easily update and modify your GUIs in wxFormBuilder again (and again...).
Advantages:
Can generate your base GUIs quite quickly, in a visual manner, without having to constantly look up the documentation.
Don't have to do as many code/compile/run cycles just to make sure your GUI is looking like what you expected.
The base class/derived class paradigm can make a reasonably clean separation of your GUI and business logic code.
Potential Disadvantages
Disclaimer: I've only used wxWidgets to create very simple, straight-forward GUIs, so haven't really pushed the tool to any limits.
Potentially the base class/derived class paradigm could sometimes get in your way if you are doing something too sophisticated with your GUI (OTOH that could indicate that you may need to re-think your approach.)
I had a situation where I needed a menu item when compiled for one operating system, but not when compiled for another. There is no logic in wxFormBuilder to support this. I ended up taking the short-cut of always creating the menu item and then having my derived class make it invisible if it was the wrong OS (not ideal.)
That's about it, I think.
|
758,041
| 758,072
|
How can I recursively search a list of lists for an item, getting the "closest" match
|
I have a class "Class" which has a member std::list, I want to search that list/tree for an item, specifically an item with a specific name.
A basic representation of my class is as follows:
#include <list>
#include <string>
class Class {
std::string _name;
std::list<Class*> _members;
public:
Class(const std::string& name) : _name(name) {}
void addMember(Class* member) { _members.push_back(member); }
const std::string& name() const { return _name; }
const std::list members() const { return _members; }
Class* findItem(const std::string& name) const { ... }
};
I could just do something like this in Class::findItem:
Class* Class::findItem(const std::string& n) const {
std::list<Class>::const_iteratior i;
for(i=_members.begin(); i!=_members.end(); ++i)
if((*i)->name() == n) return *i;
for(i=_members.begin(); i!=_members.end(); ++i) {
Class* cls = (*i)->findItem(n);
if(cls) return cls;
}
return 0;
}
But, what I want to happen is for findItem() to return the "closest" item to the one searched from.
For instance, if this is my tree, with each letter representing one level in the list hierarchy, and each number representing the items "value". I want findItem(3) to return B(3), rather than C(3).
A(1)
|
----------------------------------
B(2) B(3)
| |
--------------------- -----
C(3) C(4) C(4)
| |
---------------- ----------
D(5) D(6) D(7) D(5) D(6)
|
Use a breadth-first search. As you access a node that isn't equal to the query value, you push that node onto the back of the queue. Process nodes from the front of the queue first. The first match you find will be the one closest to the root.
Class* Class::findItem(const std::string& n) const {
std::list<Class>::const_iteratior i;
std::queue<Class*> q;
q.push(this);
while (!q.empty()) {
Class *c = q.front(); q.pop();
if (c->name() == n) return c;
for(i=c->_members.begin(); i!=c->_members.end(); ++i)
q.push(i);
}
return NULL;
}
|
758,045
| 758,143
|
How to be able to extract comments from inside a function in doxygen?
|
I'm interested to know if it is possible to have some comments in a function (c, c++, java) in a way that doxygen could put them in the generated html file.
for example:
function(...)
{
do_1();
/**
* Call do_2 function for doing specific stuff.
*/
do_2();
}
|
No, doxygen does not support comments blocks inside function bodies. From the manual:
Doxygen allows you to put your documentation blocks practically anywhere (the exception is inside the body of a function or inside a normal C style comment block).
Section: Doxygen documenting the code
|
758,118
| 758,125
|
C++ vector literals, or something like them
|
I'm writing some code against a C++ API that takes vectors of vectors of vectors, and it's getting tedious to write code like the following all over the place:
vector<string> vs1;
vs1.push_back("x");
vs1.push_back("y");
...
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1.push_back(vs1);
vvs1.push_back(vs2);
...
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs.push_back(vvs1);
vvvs.push_back(vvs2);
...
Does C++ have a vector literal syntax? I.e., something like:
vector<vector<vector<string>>> vvvs =
{ { {"x","y", ... }, ... }, ... }
Is there a non-builtin way to accomplish this?
|
In C++0x you will be able to use your desired syntax:
vector<vector<vector<string> > > vvvs =
{ { {"x","y", ... }, ... }, ... };
But in today's C++ you are limited to using boost.assign which lets you do:
vector<string> vs1;
vs1 += "x", "y", ...;
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1 += vs1, vs2, ...;
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs += vvs1, vvs2, ...;
... or using Qt's containers which let you do it in one go:
QVector<QVector<QVector<string> > > vvvs =
QVector<QVector<QVector<string> > >() << (
QVector<QVector<string> >() << (
QVector<string>() << "x", "y", ...) <<
... ) <<
...
;
The other semi-sane option, at least for flat vectors, is to construct from an array:
string a[] = { "x", "y", "z" };
vector<string> vec(a, a + 3);
|
758,151
| 758,848
|
Equivalent of OnFinalMessage for MFC windows?
|
ATL CWindow class has a useful virtual method OnFinalMessage which is called after the last window message for the window is processed - at this point it is safe to destroy or deleted any objects associated with the window. Is there any equivalent for windows derived from the MFC CWnd class?
|
This answer describes how I eventually solved my problem. I'll note that while the answer by John Dibling was helpful, this was not the final solution to my problem. This is because the WM_NC_DESTROY message is sent as the final message to the window, but this can be handled before the last message to the window has finished being handled. See for example http://support.microsoft.com/?kbid=202110 for an explanation of the problem.
DialogProc() is called with WM_CLOSE.
ProcessWindowMessage() calls your WM_CLOSE handler.
In your WM_CLOSE handler, you call DestroyWindow().
This ends up calling DialogProc again with WM_NCDESTROY.
ProcessWindowMessage() calls your WM_NCDESTROY handler.
You call "delete this" in your WM_NCDESTROY handler.
After having called delete this, the object is no longer valid, but you are still technically in the WM_CLOSE handler so you will probably crash when you eventually get back there. This means it is not really safe to assume that you can do delete this in PostNcDestroy, since the object may still be live in some other stack frame.
///
/// A window designed to allow any window to use the "OnFinalMessage" method from the ATL CWindow class
/// You must call SubclassWindow for this instance so that the window procedure runs
template<class T>
class FinalMessageWindow : public CWindowImpl<FinalMessageWindow<T> >
{
T *_t; /// The object wanting to receive the final message notification
public:
BEGIN_MSG_MAP(FinalMessageWindow<T>)
END_MSG_MAP()
///
/// The constructor
/// \param t The object that wants to get the OnFinalMessage notification
FinalMessageWindow(T *t)
: _t(t)
{
}
///
/// Called when the final window message for the window has been processed - this is often a good time to delete the object
/// \param hWnd The window handle
virtual void OnFinalMessage(HWND hWnd)
{
_t->OnFinalMessage(hWnd);
}
};
I created the above class, note that it is derived from the ATL CWindow class - this allows me to use the OnFinalMessage handler for this class. The OnFinalMessage handler is different from the PostNcDestroy in MFC windows in that it is guaranteed to be called only after the final message handler on the stack has completed.
We then use window subclassing to insert this window as the window procedure for my own window:
// roughly speaking
FinalMessageWindow<MyWindow> _finalMessageWindow(this);
finalMessageWindow.SubclassWindow(m_hWnd);
Then we implement the OnFinalMessage handler for our window:
void MyWindow::OnFinalMessage(HWND hWnd)
{
delete this;
}
|
758,182
| 758,196
|
How to check if a NULL character is in a string when debugging with WinDbg
|
For instance:
0:000> ?? testFile //check this variable
char * 0x009c6758
"e:\TEST\example.FOO"
Question:
How can I check for a NULL-terminated character in above?
|
It's clearly there since you are seeing a valid string and not several junk characters afterwards.
db poi(testFile)
Will dump the raw bytes in the string to the console and you'll be able to see a 0 byte at the end. You can also use the memory window to see the zero byte at the end of the string as well.
|
758,673
| 758,722
|
Uses for multiple levels of pointer dereferences?
|
When does using pointers in any language require someone to use more than one, let's say a triple pointer. When does it make sense to use a triple pointer instead of just using a regular pointer?
For example:
char * * *ptr;
instead of
char *ptr;
|
each star should be read as "which pointed to by a pointer" so
char *foo;
is "char which pointed to by a pointer foo". However
char *** foo;
is "char which pointed to by a pointer which is pointed to a pointer which is pointed to a pointer foo". Thus foo is a pointer. At that address is a second pointer. At the address pointed to by that is a third pointer. Dereferencing the third pointer results in a char. If that's all there is to it, its hard to make much of a case for that.
Its still possible to get some useful work done, though. Imagine we're writing a substitute for bash, or some other process control program. We want to manage our processes' invocations in an object oriented way...
struct invocation {
char* command; // command to invoke the subprocess
char* path; // path to executable
char** env; // environment variables passed to the subprocess
...
}
But we want to do something fancy. We want to have a way to browse all of the different sets of environment variables as seen by each subprocess. to do that, we gather each set of env members from the invocation instances into an array env_list and pass it to the function that deals with that:
void browse_env(size_t envc, char*** env_list);
|
759,274
| 759,294
|
What is the lifetime and validity of C++ iterators?
|
I'm planning to implement a list of Things in C++ where elements might be removed out of order. I don't expect that i'll need any kind of random access (i just need to sweep the list periodically), and the order of items isn't important either.
So I thought of std::list<Thing*> with this->position = insert(lst.end(), thing) should do the trick. I'd like the Thing class to remember the position of each instance so that i can later easily do lst.erase(this->position) in constant time.
However, i'm still a bit new to C++ STL containers, and i don't know if it's safe to keep iterators for such a long time. Especially, given that there will be other elements deleted ahead and after the inserted Thing before it's gone.
|
In list all iterators remain valid during inserting and only iterators to erased elements get invalid during erasing.
In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*.
EDIT:
Additional details for vector and deque:
Vector:
inserting --- All iterators get
invalid if reallocation happens,
otherwise its valid.
erasing ---- All iterators after
erase point get invalid.
deque:
inserting --- All iterators get
invalid.
erasing ---- All iterators get
invalid.
|
759,315
| 759,359
|
Does const_cast ever cause actual code emission?
|
Is it true that const_cast is just a way to tell the compiler "stop moaning, treat this as a non-const pointer"? Are there any cases when const_cast itself is translated into actual machine code?
|
Conceivably,there could be architectures where a const pointer had a different representation to a non-const one, in which case the compiler would have to emit some code. I'm not aware of any such architectures, however.
|
759,341
| 759,349
|
Programatically opening and closing a console
|
I'm writing a windowed program in C++, but I would like to have the option to pop up a console to output to from inside the program (such as various things that go on behind the scenes of my program, to see that everything is acting correctly). Is there an easy way to do this?
EDIT:
In this particular case I'm using sfml on windows, but for the purposes of this question it can be any API or platform (and platform independent solutions are best)
|
If you are talking about MS Windows, which your question does not make clear, you can use the AllocConsole API to create a console. for your app.
Edit: You say that it could be any platform, but this is not so as many platforms have no concept of a console. For this reason, a cross-platform solution is not possible.
|
759,366
| 760,216
|
Spawned child exits with state = 127
|
I use posix_spawnp to execute different processes and I check the status (with waitpid) to make sure the child was created properly
int iRet = posix_spawnp(&iPID, zPath, NULL, NULL, argv, environ);
if (iRet != 0)
{
return false;
}
int iState;
waitpid(static_cast<pid_t>(iPID), &iState, WNOHANG);
cout << "Wait: PID " << iPID << " | State " << iState << endl;
if (WIFEXITED(iState)) {
printf("Child exited with RC=%d\n",WEXITSTATUS(iState));
}
else if (WIFSIGNALED(iState)) {
printf("Child exited via signal %d\n",WTERMSIG(iState));
}
else
{
printf("Child is NORMAL");
}
At first this executes properly and I get the following message:
Wait: PID 15911 | State 0 Child exited
with RC=0
After executing the same process several times, the child process starts to exit with status 127.
Wait: PID 15947 | State 32512 Child
exited with RC=127
After this happens, I could not get the child to spawn again. I enclosed the section of code given above in a for loop but it wouldn't spawn properly.
If I restart the parent process, it works for a while but the same problem crops up again after a while.
What am I doing wrong here?
|
Check this link.
For example:
EINVAL The value specified by file_actions or attrp is invalid.
The error codes for the posix_spawn and posix_spawnp subroutines are affected by the following conditions:
If this error occurs after the calling process successfully returns from the posix_spawn or posix_spawnp function, the child process might exit with exit status 127.
It looks as if it might exit with 127 for a whole host of reasons.
|
759,512
| 759,536
|
Internal typedefs in C++ - good style or bad style?
|
Something I have found myself doing often lately is declaring typedefs relevant to a particular class inside that class, i.e.
class Lorem
{
typedef boost::shared_ptr<Lorem> ptr;
typedef std::vector<Lorem::ptr> vector;
//
// ...
//
};
These types are then used elsewhere in the code:
Lorem::vector lorems;
Lorem::ptr lorem( new Lorem() );
lorems.push_back( lorem );
Reasons I like it:
It reduces the noise introduced by the class templates, std::vector<Lorem> becomes Lorem::vector, etc.
It serves as a statement of intent - in the example above, the Lorem class is intended to be reference counted via boost::shared_ptr and stored in a vector.
It allows the implementation to change - i.e. if Lorem needed to be changed to be intrusively reference counted (via boost::intrusive_ptr) at a later stage then this would have minimal impact to the code.
I think it looks 'prettier' and is arguably easier to read.
Reasons I don't like it:
There are sometimes issues with dependencies - if you want to embed, say, a Lorem::vector within another class but only need (or want) to forward declare Lorem (as opposed to introducing a dependency on its header file) then you end up having to use the explicit types (e.g. boost::shared_ptr<Lorem> rather than Lorem::ptr), which is a little inconsistent.
It may not be very common, and hence harder to understand?
I try to be objective with my coding style, so it would be good to get some other opinions on it so I can dissect my thinking a little bit.
|
I think it is excellent style, and I use it myself. It is always best to limit the scope of names as much as possible, and use of classes is the best way to do this in C++. For example, the C++ Standard library makes heavy use of typedefs within classes.
|
759,584
| 759,609
|
c++ #define a macro with brackets?
|
Instead of doing the following everytime
start();
// some code here
stop();
I would like to define some sort of macro which makes it possible to write like:
startstop()
{
//code here
}
Is it possible in C++?
|
You can do something very close using a small C++ helper class.
class StartStopper {
public:
StartStopper() { start(); }
~StartStopper() { stop(); }
};
Then in your code:
{
StartStopper ss;
// code here
}
When execution enters the block and constructs the ss variable, the start() function will be called. When execution leaves the block, the StartStopper destructor will be automatically called and will then call stop().
|
759,728
| 761,959
|
Problem nesting boost::lambda::bind-s
|
I have a generic function:
void ImageAlbum::ExpressButtonPressed(
boost::function<
void (
thumb::PhotoPrintThumbnail*,
thumb::PhotoPrintFormat,
thumb::PhotoPrintQuantity
)
> memberToCall
) {
...
BOOST_FOREACH(thumb::PhotoPrintThumbnail *pThumbnail, m_thumbs.GetSelected()) {
memberToCall(
pThumbnail,
m_expressSel.GetSelectedFormat(),
m_expressSel.GetSelectedQuantity()
);
}
...
}
I can successfully call:
ExpressButtonPressed(boost::bind(&thumb::PhotoPrintThumbnail::AddQuantity, _1, _2, _3));
Then, instead of adding a quantity of a certain format to a thumbnail, I need to replace them all with a single format. More precise, with a list of 1 element, like that:
ExpressButtonPressed(
boost::lambda::bind(
&thumb::PhotoPrintThumbnail::SetFormats,
_1,
boost::lambda::bind(
boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormats>(),
1,
boost::lambda::bind(
boost::lambda::constructor<thumb::PhotoPrintThumbnail::LoadedFormat>(),
_2,
_3
)
)
)
);
Which results in "boost/lambda/detail/actions.hpp(96) : error C2665: 'boost::lambda::function_adaptor::apply' : none of the 2 overloads could convert all the argument types".
What am I doing wrong here?
BTW
class PhotoPrintThumbnail {
public:
...
typedef std::pair<PhotoPrintFormat, PhotoPrintQuantity> LoadedFormat;
typedef std::list<LoadedFormat> LoadedFormats;
void SetFormats(const LoadedFormats &formats);
|
Do you happen to #include boost/bind.hpp in your lambda-using code? This would cause unqualified use of the placeholders (_1, _2, etc) to resolve to those defined by Boost.Bind, and these don't mix well with Boost.Lambda.
Rewriting your code to explicitly use boost::lambda::_[1,2,3] instead of the unqualified names compiles fine on my VC 7.1 setup.
|
759,920
| 759,943
|
Need user to input string /check string length (C++)
|
I'll need to accept a string of 5 numbers from the user (only 5).
Should I use
istringstream
for the same ?
Can't I get away with something like this ?
int main()
{
char *InputMain;
InputMain=(char *)malloc(5+1);
cout << "Enter the number : " <<endl;
cin.getline ( InputMain, 5, '\n' ); // Input goes into InputMain
cout << "The number entered is : " << InputMain <<endl;
cin.get();
}
Then comes the next part..
How'd I make sure the user inputs only 5 chars? And maybe if the user enters more than 5 chars, I should display a warning saying only 5 chars allowed..
One more question, since this essentially is a string, I'll need to validate the input to be only numbers by parsing through each char in the string and checking against respective ASCII values (for numerals).. Is that approach the right thing?
|
Unfortunately there is no portable way to restrict the number of characters input in C++. But whatever platform you are using will provide some mechanism: for example on Windows, look up Console functions.
If you do go with plain old C++ iostreams input from cin, it's a good idea to read the initial text into a std::string using istream& getline(istream&, string&) -- this will prevent buffer overflows, because strings resize as necessary. (Your code involving getline(InputMain, 5, '\n') is technically safe in that it won't read more than 5 characters into InputMain, but this code is fragile -- if you later decide you want 6 characters, you could easily forget to update your call to malloc(), leading to crashes. Also, you need to remember to free(InputMain). But as I said, use string instead.)
Regarding parsing:
Whether you read the input into a string using getline(cin, str) or some platform-specific code, once it's in there you need to get it out in the form of a number. This is where the istringstream class is useful -- it lets you treat an existing string as a stream to read from, so you can use the formatted input >> operator:
string str;
if (!getline(cin, str)) {
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) {
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
} else if (i < 1000 || i > 9999) {
cerr << "Out of range!\n";
} else {
// Process i
}
If you're using C++ iostreams, you can actually just extract directly from cin instead of going via a string and an istringstream:
int i;
cin >> i; // Extract an integer value from cin
However this can have subtle undesirable effects; notably, any additional characters on the line typed by the user (in particular the '\n' typed when they press Enter) will remain in the input buffer to be read by the next << operation. Often this doesn't matter, but sometimes it does: e.g. if you follow up with cin.get();, expecting that this will wait for a keypress, it won't -- it will just read the '\n' (or the first non-digit character the user typed).
|
760,030
| 760,037
|
What does the suffix #DEN mean on the value of a variable
|
When debugging in VS2005 I have a float in the Locals window whose values is:
1.744e-039#DEN
What does the #DEN signify/stand for?
|
This is for "denormalized number".
|
760,114
| 760,631
|
What would you use to implement a fast and lightweight file server?
|
I need to have as part of a desktop application a file server which should respond as fast as possible to file transfer requests (from remote clients, usually located on the same LAN). There will be many file requests for small sized files. The server should be able to provide both upload and download services.
I am not tight to any particual technology so I am open to any programming language, toolkits, libraries as long as they can run on Windows.
My initial take is to go with a C/C++ implementation using Windows Sockets or use the services provided by libraries such as Boost (asio or such). I have also thought of Erlang but that I'll have to learn and so the performance benefits should justify the increased development time due to having to learn the language.
LATER EDIT: I appreciate the answers that say use FTP or HTTP or basically anything that has been already created but considering you still want to write one from scratch, what would you do?
|
For frequent uploads of small files, the fastest way would be to implement your own proprietary protocol, but that would require a considerable amount of work - and also it would be non-standard, meaning future integration would be difficult unless you are able to implement your protocol in any client you'll support. If you choose to do it anyway, this is my suggestion for a simple protocol:
Command: 1 byte to identify what'll be done: (0x01 for upload request, 0x02 for download request, 0x11 for upload response, 0x12 for download response, etc).
File name: can be fixed-size or prefixed with a byte for the length (assuming the name is less than 255 bytes)
Checksum, MD5 for instance (if upload request or download response)
File size (if upload request or download response)
payload (if upload request or download response)
This could be implemented on top of a simple TCP socket. You can also use UDP, avoiding the cost of establishing a connection but in this case you have to deal with retransmission control.
Before deciding to implement your own protocol, take a look at HTTP libraries like libcurl, you could make your server use standard HTTP commands like GET for download and POST for upload. This would save a lot of work and you'll be able to test the download with any web browser.
Another suggestion to improve performance is to use as the file repository not the filesystem, but something like SQLite. You can create a single table containing one char column for the file name and one blob column for the file contents. Since SQLite is lightweight and does an efficient caching, you'll most of the time avoid the disk access overhead.
I'm assuming you don't need client authentication.
Finally: although C++ is your preference to give you raw native code speed, rarely this is the major bottleneck in this kind of application. Most probably will be disk access and network bandwidth. I'm mentioning this because in Java you'll probably be able to make a servlet to do exactly the same thing (using HTTP GET for download and POST for upload) with less than 100 lines of code. Use Derby instead of SQLite in this case, put that servlet in any container (Tomcat, Glassfish, etc) and it's done.
|
760,221
| 760,234
|
Breaking in std::for_each loop
|
While using std::for_each algorithm how do I break when a certain condition is satisfied?
|
You can use std::find_if algorithm, which will stop and return the iterator to the first element where the predicate condition applied to returns true. So your predicate should be changed to return a boolean as the continue/break condition.
However, this is a hack, so you can use the algorithms.
Another way is to use BOOST_FOREACH.
|
760,301
| 760,350
|
Implementing a no-op std::ostream
|
I'm looking at making a logging class which has members like Info, Error etc that can configurably output to console, file, or to nowhere.
For efficiency, I would like to avoid the overhead of formatting messages that are going to be thrown away (ie info messages when not running in a verbose mode). If I implement a custom std::streambuf that outputs to nowhere, I imagine that the std::ostream layer will still do all the formatting. Can anyone suggest a way to have a truly "null" std::ostream that avoids doing any work at all on the parameters passed to it with <<?
|
To prevent the operator<<() invocations from doing formatting, you should know the streamtype at compile-time. This can be done either with macros or with templates.
My template solution follows.
class NullStream {
public:
void setFile() { /* no-op */ }
template<typename TPrintable>
NullStream& operator<<(TPrintable const&)
{ return *this; } /* no-op */
}
template<class TErrorStream> // add TInfoStream etc
class Logger {
public:
TErrorStream& errorStream() {
return m_errorStream;
}
private:
TErrorStream m_errorStream;
};
//usage
int main() {
Logger<std::ofstream> normal_logger; // does real output
normal_logger.errorStream().open("out.txt");
normal_logger.errorStream() << "My age is " << 19;
Logger<NullStream> null_logger; // does zero output with zero overhead
null_logger.errorStream().open("out.txt"); // no-op
null_logger.errorStream() << "My age is " << 19; // no-op
}
Since you have to do this at compile-time, it is of course quite inflexible.
For example, you cannot decide the logging level at runtime from a configuration file.
|
760,522
| 761,143
|
ACE vs Boost vs Poco vs wxWidgets
|
I have a considerable amount of experience with ACE, Boost and wxWidgets. I have recently found the POCO libraries. Does anyone have any experience with them and how they compare to ACE, Boost and wxWidgets with regard to performance and reliability?
I am particularly interested in replacing ACE with POCO. I have been unable to get ACE to compile with VS2008 with an x64 target. I mostly use ACE_Task so I think I can replace those with Poco's threads and message queues.
Some other portions of POCO that interest me are the HTTPServer, HTTPClient, and LayeredConfiguration. Those libraries are similiar to libraries in Boost and wxWidgets but I try to limit my use of wxWidgets to GUI components and the comparable Boost libraries are... difficult.
I'm interested in any experience anyone can share about POCO, good or bad.
|
I have used parts of POCO now and again and found it to be a very nice lib. I largely abandoned ACE a number of years ago but POCO contains some of the same patterns - Task, Reactor, etc. I have never had any problems with it so I have to assume it is stable.
Some aspects that I like:
it is a pretty well integrated OOP hierarchy so the components work well with each other. It has a much more cohesive feel than something like Boost which is rather piece-meal.
the source code is available and very clear. You don't need to devote large blocks of time to understand what it is doing (ACE, at least last I looked at the source) or be a template wizard (Boost).
Components stick close to standard C++. Exceptions are derived from std::exception; they didn't reinvent yet-another-string class, etc.
It is surprising comprehensive. There is a lot more there than appears at first glance.
The downside:
A matter of personal preference but the authors stick pretty much to a one class per header file model so you end up including a lot of different files.
Limited documentation. Mostly doxygen type API pages and a couple of PDFs pointing to source examples. It's usable but considering the size of the lib it is initially difficult to figure if you are making the best use of the components.
If there is an active community built around it, I never found it. The package is maintained by some European based company and they had a wiki but I didn't find it that active or useful.
All things considered, the downside is pretty minor. I think it is a very good library and would definitely recommend it.
|
760,578
| 760,593
|
Const reference to temporary
|
After reading this article on Herb Sutter's blog, I experimented a bit and ran into something that puzzles me. I am using Visual C++ 2005, but I would be surprised if this was implementation dependent.
Here is my code:
#include <iostream>
using namespace std;
struct Base {
//Base() {}
~Base() { cout << "~Base()" << endl; }
};
int main()
{
const Base & f = Base();
}
When run, it displays "~Base()" twice... But if I un-comment the constructor, it displays it only once!
Does anyone have an explanation for this?
|
This IS implementation dependent.
The standard allows a copy to occur when binding a temporary to a const reference. In your case, VC++ performs a copy only when the constructor is implicitly defined. This is unexpected, but permitted.
C++1x will fix this.
|
760,777
| 760,801
|
C++ getters/setters coding style
|
I have been programming in C# for a while and now I want to brush up on my C++ skills.
Having the class:
class Foo
{
const std::string& name_;
...
};
What would be the best approach (I only want to allow read access to the name_ field):
use a getter method: inline const std::string& name() const { return name_; }
make the field public since it's a constant
Thanks.
|
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
|
760,790
| 760,796
|
Is it legal to write to std::string?
|
In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via operator[] and I can write to it.
For example, if I have function:
void toupper(char *first,char *last_plus_one);
I can write directly to vector getting a pointer to the first element:
vector<char> message // has "Some Message";
toupper(&message[0],&message[0]+message.size());
Can I do same thing with std::string?
string message="Some Message";
toupper(&message[0],&message[0]+message.size());
Does the standard guarantee that the location of the memory is actually linear? ie:
&(*(message.begin()+n)) == &message[n]
Thanks.
|
std::string will be required to have contiguous storage with the new c++0x standard. Currently that is undefined behavior.
|
761,256
| 761,289
|
How do you "refactor" ant build.xml files?
|
I'm working on a large C++ system built with ant+cpptasks. It works well enough, but the build.xml file is getting out of hand, due to standard operating procedure for adding a new library or executable target being to copy-and-paste another lib/exe's rules (which are already quite large). If this was "proper code", it'd be screaming out for refactoring, but being an ant newbie (more used to make or VisualStudio solutions) I'm not sure what the options are.
What are ant users' best-practices for stopping ant build files exploding ?
One obvious option would be to produce the build.xml via XSLT, defining our own tags for commonly recurring patterns. Does anyone do that, or are there better ways ?
|
you may be interested in:
<import>
<macrodef>
<subant>
Check also this article on "ant features for big projects".
|
761,616
| 761,642
|
XML Serialization of DOM Portions with Xerces C++
|
I've been struggling quite a bit with Xerces C++ and my unfamiliarity with all that is XML, but I need to use XML for a project I'm working on.
My question is how do I serialize portions of a DOM tree that I have already parsed and created of out of a XML instance document (validated against a schema I wrote) so that I can create many new instance documents (still containing the root element of the original document) in a way that they remain valid against my schema?
To be more specific, I have a large instance document with thousands of sets contained within a single root element that I need to individually place into separate files for later processing. Basically a large set of sets which need to each be placed into individual files and still validate separately.
I'm lost on the whole process of how to do this. I've not had any luck finding examples that serialize portions of a DOM tree and I find a lot of the terminology surrounding XML related documentation less than helpful.
|
Does this article (Section: XML Schema validation using serialization of grammars to disk) help?
We have successfully used the MemBufFormat described here.
|
761,655
| 761,694
|
What is the naming convention when typdef complex STL maps?
|
1) What is the convention used in practice when typedef'ing
something like
typedef std::map<SomeClass*, SomeOtherClass> [SomeStandardName>]
typedef std::map<SomeClass*, std<SomeOtherClass> > <[SomeStandardName]
2) Where do you usually put typedef: header files globally, local to the class?
3) Do you typedef iterators or const map<> version?
4) Say you have map that used by two different concepts, do you create two separate typedefs them?
typedef map<string, SomeClass *> IDToSomeClassMap;
typedef map<string, SomeClass *> DescriptionToSomeClassMap;
Thanks
Edit #1
I am interested specifically in typedef STL maps, such as
typedef map<int, string> IdToDescriptionMap
or
typedef map<int, string> IdToDescription
What are common practices?
|
I prefer the following convention:
typedef std::map< Foo, Bar > FooToBarMap
I purposely avoid typedef'ing the iterators, I prefer explicitly referring to them as:
FooToBarMap::const_iterator
Since the iterators are already a de facto standard typename. And FooToBarMapConstIter is actually less clear to read when skimming code, I find.
|
761,791
| 761,811
|
Converting Between Local Times and GMT/UTC in C/C++
|
What's the best way to convert datetimes between local time and UTC in C/C++?
By "datetime", I mean some time representation that contains date and time-of-day. I'll be happy with time_t, struct tm, or any other representation that makes it possible.
My platform is Linux.
Here's the specific problem I'm trying to solve: I get a pair of values containing a julian date and a number of seconds into the day. Those values are in GMT. I need to convert that to a local-timezone "YYYYMMDDHHMMSS" value. I know how to convert the julian date to Y-M-D, and obviously it is easy to convert seconds into HHMMSS. However, the tricky part is the timezone conversion. I'm sure I can figure out a solution, but I'd prefer to find a "standard" or "well-known" way rather than stumbling around.
A possibly related question is Get Daylight Saving Transition Dates For Time Zones in C
|
You're supposed to use combinations of gmtime/localtime and timegm/mktime. That should give you the orthogonal tools to do conversions between struct tm and time_t.
For UTC/GMT:
time_t t;
struct tm tm;
struct tm * tmp;
...
t = timegm(&tm);
...
tmp = gmtime(t);
For localtime:
t = mktime(&tm);
...
tmp = localtime(t);
All tzset() does is set the internal timezone variable from the TZ environment variable. I don't think this is supposed to be called more than once.
If you're trying to convert between timezones, you should modify the struct tm's tm_gmtoff.
|
761,893
| 761,915
|
error: cast from 'const prog_uchar*' to 'byte' loses precision?
|
The error is at this line :
dataArray[iLedMatrix][iRow] |= (byte)(bufferPattern[iRow]) & (1<<7);
dataArray is : byte dataArray[NUMBER_LED_MATRIX][NUMBER_ROW_PER_MATRIX];
bufferPattern is : const patternp * bufferPattern;
patternp is a typedef of the type : typedef prog_uchar patternp[NUM_ROWS];
I can see in the Reference that prog_uchar is 1 byte ( 0 to 255 ). So I do not understand the error about losing precision? Any idea?
|
The problem is in this sub expression
(byte)(bufferPattern[iRow])
The variable bufferPattern is of type const patternp * so when the indexer is applied the result is patternp. The type "patternp" is typedef to prog_uchar[]. So in actuality this expression is saying
Cast a prog_uchar* to a byte
Byte is almost certainly a single byte value and prog_uchar* is the platform specific pointer type (either 4 or 8 bytes). This does indeed result in a loss of precision. Perhaps you meant to dereferenc this value?
(byte)(*(bufferPattern[iRow]))
|
761,917
| 763,451
|
Handling a class with a long initialization list and multiple constructors?
|
I have a (for me) complex object with about 20 data member, many of which are pointer to other classes. So for the constructor, I have a big long, complex initialization list. The class also has a dozen different constructors, reflecting the various ways the class can be created. Most of these initialized items are unchanged between each of these different constructors.
My concern here is that I now have a large chuck of copied (or mostly copied) code which, if I need to add a new member to the class, may not make it into each of the constructor initialization lists.
class Object
{
Object();
Object(const string &Name);
Object (const string &Name, const string &path);
Object (const string &Name, const bool loadMetadata);
Object (const string &Name, const string &path, const bool loadMetadata);
}
Object::Object() :
name(),
parent_index (0),
rowData (new MemoryRow()),
objectFile (),
rows (new MemoryColumn (object_constants::RowName, OBJECTID, object_constants::ROWS_OID)),
cols (new MemoryColumn (object_constants::ColName, OBJECTID, object_constants::COLS_OID)),
objectName (new MemoryColumn(object_constants::ObjName, STRING, object_constants::short_name_len, object_constants::OBJECTNAME_OID)),
parent (new MemoryColumn(object_constants::ParentName, STRING, object_constants::long_name_len, object_constants::PARENT_OID)),
parentIndex (new MemoryColumn(object_constants::ParentIndex, OBJECTID, object_constants::PARENTINDEX_OID)),
childCount (new MemoryColumn (object_constants::ChildCount, INTEGER, object_constants::CHILD_COUNT_OID)),
childList (new MemoryColumn (object_constants::ChildList, STRING, object_constants::long_name_len, object_constants::CHILD_OID)),
columnNames (new MemoryColumn (object_constants::ColumnNames, STRING, object_constats::short_name_len, object_constants::COLUMN_NAME)),
columnTypes (new MemoryColumn (object_constants::ColumnTypes, INTEGER, object_constants::COLUMN_TYPE)),
columnSizes (new MemoryColumn (object_constants::ColumnSizes, INTEGER, object_constants::COLUMN_SIZE))
{}
Then repeat as above for the other constructors. Is there any smart way of using the default constructor for this, then modifying the results for the other constructors?
|
How about refactor the common fields into a base class. The default constructor for the base class would handle initialization for the plethora of default fields. Would look something like this:
class BaseClass {
public:
BaseClass();
};
class Object : public BaseClass
{
Object();
Object(const string &Name);
Object (const string &Name, const string &path);
Object (const string &Name, const bool loadMetadata);
Object (const string &Name, const string &path, const bool loadMetadata);
};
BaseClass::BaseClass() :
parent_index (0),
rowData (new MemoryRow()),
objectFile (),
rows (new MemoryColumn (object_constants::RowName, OBJECTID, object_constants::ROWS_OID)),
cols (new MemoryColumn (object_constants::ColName, OBJECTID, object_constants::COLS_OID)),
objectName (new MemoryColumn(object_constants::ObjName, STRING, object_constants::short_name_len, object_constants::OBJECTNAME_OID)),
parent (new MemoryColumn(object_constants::ParentName, STRING, object_constants::long_name_len, object_constants::PARENT_OID)),
parentIndex (new MemoryColumn(object_constants::ParentIndex, OBJECTID, object_constants::PARENTINDEX_OID)),
childCount (new MemoryColumn (object_constants::ChildCount, INTEGER, object_constants::CHILD_COUNT_OID)),
childList (new MemoryColumn (object_constants::ChildList, STRING, object_constants::long_name_len, object_constants::CHILD_OID)),
columnNames (new MemoryColumn (object_constants::ColumnNames, STRING, object_constats::short_name_len, object_constants::COLUMN_NAME)),
columnTypes (new MemoryColumn (object_constants::ColumnTypes, INTEGER, object_constants::COLUMN_TYPE)),
columnSizes (new MemoryColumn (object_constants::ColumnSizes, INTEGER, object_constants::COLUMN_SIZE))
{}
Your Object constructors should look a little more manageable, now:
Object::Object() : BaseClass() {}
Object::Object (const string &Name): BaseClass(), name(Name) {}
Object::Object (const string &Name, const string &path): BaseClass(), name(Name), path_(path){}
Object::Object (const string &Name, const bool loadMetadata): BaseClass(), name(Name){}
Object::Object (const string &Name, const string &path, const bool loadMetadata): BaseClass(), path_(path) {}
Similar in nature to Iraimbilanja's answer, but avoids adding an inner-class for accessing data, which might impact a lot of existing code. If you've already got a class hierarchy, though, it may be difficult to factor it into a base class.
|
761,930
| 762,012
|
Getting Object Functionality out of C++ code in C#
|
I have have a function in wrote in C++ that calls some functions in a old lib. This function creates some memory makes the calls and destroys the memory. To optimize this I would create an object that would keep the memory allocated until the object was destroyed. However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables.
My idea is instead this; Think of the DLL as a class and the use local vars inside the scope of the dll to point to memory. Then have a function to create the memory, call the worker functions and another to destroy the memory when done with the DLL.
Is this a good approach? Is there a better way?
|
I prefer to write a managed wrapper in C++/CLI (formerly Managed C++), as it makes it much easier to explicitly do what you want with managed/unmanaged interoperability on the C++ side, and your C# doesn't get polluted with P/Invoke style code.
Edit Just noticed your comment "However I'm going to be calling this function from C# and don't believe I can export a Class, just functions or variables."
That's not entirely true - C# can import full classes from an assembly generated from C++/CLI code.
|
762,736
| 762,850
|
Server Design and Implementation
|
I've work in embedded systems and systems programming for hardware interfaces
to date. For fun and personal knowledge, recently I've been trying to learn more about server programming after getting my hands wet with Erlang. I've been going back and thinking about servers from a C++/Java prospective, and now I wonder how scalable systems can be built with technology like C++ or Java.
I've read that due to context-switching and limited memory, a per-client thread handler isn't realistic. Usually a thread-pool is created and a mix of worker-threads and asynchronous I/O is used to handle requests. I wonder, first of all, how does one determine the thread pool size? Does one simply have to measure and find the optimal balance? Eventually as the system scales then perhaps more than one server is needed to handle requests. How are requests managed across mulitple servers handling a large client base?
I am just looking for some direction into where I might be able to read more and find answers to my questions. What area of computer science would I look into for more information in this area? Are there any design patterns for this area of computing?
|
for C++ I've used boost::asio, it's very modern C++, and quite plesant to work with. Also the C++0x network libraries will be based on ASIO's implementation, so it's valuable knowledge.
As for designs 1thread per client, doesn't work, as you've already learned. And for high performance multithreading the best number of threads seems to be CoresX2, but for servers, there is lots of IO per request, which means lots of idle waiting. And from experience, looking at Apache, MySQL, and Oracle the amount of threads is about CoresX10 for database servers, and CoresX40 for web servers, not saying these are the ideals, but they seem to be patterns of succesful systems, so if your system can be balanced to work optimally with similar numbers atleast you'll know your design isn't completely lousy.
|
762,852
| 762,942
|
C/C++ replacement/redefinition rules?
|
I am not particularly new to C/C++ but today I discovered some things that I didn't expect.
This compiles in gcc:
/* test.c */
#include <stddef.h> // !
typedef unsigned long int size_t; // NO ERROR
typedef unsigned long int size_t; // NO ERROR
int
main(void)
{
typedef unsigned long int size_t; // NO ERROR
return 0;
}
This doesn't:
/* test.c */
#include <stddef.h>
typedef unsigned long int size_t; // NO ERROR
typedef unsigned long int size_t; // NO ERROR
int
main(void)
{
typedef unsigned long int size_t; // NO ERROR
typedef unsigned long int size_t; // ERROR
return 0;
}
This doesn't either:
/* test.h */ // ! header
typedef unsigned long int size_t;
typedef unsigned long int size_t; // ERROR
Similarly in g++ this compiles:
/* test.h */ // ! header
#include <cstddef>
inline void* operator new(size_t, void* p) throw() { return p; }
This doesn't:
/* test.h */ // ! header
#include <new> // !
inline void* operator new(size_t, void* p) throw() { return p; } // ERROR
This does:
/* test.cc */
#define _NEW
#include <new> // !
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
inline void* operator new(size_t size) throw() // NO ERROR EXPECTED
{
cout << "OPERATOR NEW CALLED" << endl;
return malloc(size);
}
inline void* operator new(size_t, void* p) throw() // NO ERROR
{
cout << "PLACEMENT NEW CALLED" << endl;
return p;
}
int main()
{
char *buffer[4];
int *i = new (buffer) int;
int *j = new int;
return 0;
}
(Replacing the standard new operator works in all of the above cases. Replacing the replacement new operator is illegal, I know.)
It is easy to see a pattern, but can somebody offer me a "standard" explanation?
Why can I do things in .c or .cc files that I can't in .h files (redefine old typedefs, replace functions that are illegal to replace)?
Thanks for the reply. I have omitted some code including the header guards. In the last .cc example, I HTML encoded << as & g t ; & g t ; by mistake and forgot to include cstdlib.
I have fixed the code so it compiles. However, another thing that I had omitted was #define _NEW, which proved crucial. Apparently in GNU the header guard of <new> defines _NEW, so my defining it here prevented the inclusion of the standard new header, so I the replacement worked
m@m:~/Desktop/Library$ ./a.out
PLACEMENT NEW CALLED
OPERATOR NEW CALLED
So yeah, the only thing that is left unexplained is how come I can re-typedef stuff in .c/.cc files multiple times but not in .h like so:
/* test.c */
#include <stddef.h>
typedef unsigned long int size_t; // NO ERROR
typedef unsigned long int size_t; // NO ERROR
int
main(void)
{
typedef unsigned long int size_t; // NO ERROR
return 0;
}
Not that I want to do that anyway, but just wondering.
EDIT: Thanks, that really answers all of it. Changing it to xyz does not allow multiple definitions in a given scope, which feels right. :)
The reason why I was doing these little tests is that I am writing a subset of C and C++ for a small operating system but since I am using the existing libraries without removing anything to assist me in the testing of mine, I was trying to figure out how to ensure that (1) my code is being called in the tests (e.g my placement new) and (2) that my code doesn't clash with the GNU libraries.
The answer to (1) now seems pretty obvious. I just #define the header guard macro from the standart X.h into my X.h :).
|
Using GCC 4.0.1 on MacOS X 10.4.11 (ancient - but so's the computer), the example with "test.h" works - or my adaptation of it does. It appears you can have as many (identical) global typedefs of 'size_t' as you like - I had 5 with the version in stddef.h.
The first typedef inside main is 'obviously' legal; it is a new scope and can define a new meaning for the name.
The C99 Rationale says:
In C89, a typedef could be redeclared in an inner block with a declaration that explicitly contained a type name. This rule avoided the ambiguity about whether to take the typedef as the type name or a candidate for redeclaration. In C99, implicit int declarations are not allowed, so this anbiguity [sic!] is not possible and the rule is no longer necessary.
Later on, discussing standard headers, it also says:
The C89 Committee decided to make library headers “idempotent,” that is, they should be
includable any number of times, and includable in any order. This requirement, which reflects
widespread existing practice, may necessitate some protective wrappers within the headers to
avoid, for instance, redefinitions of typedefs. To ensure that such protective wrapping can be
made to work, and to ensure proper scoping of typedefs, standard headers may only be included outside of any declaration.
Clearly, therefore, redefinitions of a typedef in a single scope (e.g. the file scope) is not allowed in general.
I think, therefore, that the multiple external redefinitions of size_t is probably either a feature of GCC or a bug - actually, a feature.
If you change size_t to xyz, you get many more errors.
|
763,213
| 763,218
|
What would this code do? (memory management)
|
char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;
Btw this is not a test or anything i actually need to know this :)
|
// allocate memory for 200 chars
// p points to the begining of that
// block
char *p = new char[200];
// we don't know if allocation succeeded or not
// no null-check or exception handling
// **Update:** Mark. Or you use std::no_throw or set_new_handler.
// what happens next is not guranteed
// p1 now points to the same location as p
char *p1 = p;
// another pointer to char which points to the
// 100th character of the array, note that
// this can be treated as a pointer to an array
// for the remaining 100-odd elements
char *p2 = &p[100];
// free the memory for 200 chars
delete [] p1;
// **Update:** Doug. T
// [...] p and p2 are now pointing to freed memory
// and accessing it will be undefined behavior
// depending on the executing environment.
|
763,429
| 763,798
|
For boost-asio network programming whats the best approach for processing the response?
|
Im new to network programming and in particular to async-processes.
Start also new with the boost-lib
Im implementing a class, to access an imap-server. I can send and receive the
commands and the response, in general
The response is queued in a dequeue inside the class.
I put simple the response lines in the queue, for further processing.
What's now the best way to process the queued response?
An extra thread to check(time based) the queue, for new entries?
Each time a new entries is pushed to the queue make some callback?
How can I implement and integrate this callback?
Maybe someone have a short example for this.
Thanks
|
Each time a new entries is pushed to the queue make some callback?
How can I implement and integrate this callback?
I assume you are working with single thread synchronous connection.
Do something like that:
class worker {
deque<message> messages;
bool is_writing_;
push_message(message msg) {
messages.push_back(msg);
notify();
}
void notify()
{
if(!is_writing_) {
is_writing_=true;
init();
}
}
void init()
{
if(messages.empty()) { is_writing_=false; return; }
messamge msg=messages.pop();
convert_to_vector(v);
async_write(socket,buffer(v),
boost::bind(&worker::complete,this,placehoders::error));
}
void complete(error_code const &e)
{
if(!e) {
init();
}
else { cleanup(); }
}
};
Note!!!
This is single thread implementation. If you want notify from other thread you should
not call some_worker->push_message(msg), you should use iosrvice:
service.post(boost::bind(&worker::push_message,some_worker,msg));
And push_message would be called from the same thread that runs ioservice.
|
763,520
| 763,523
|
Deleting a char array
|
This question is related to this one. Given this code:
char *p = new char[200];
delete[] p;
what would happen if you set p[100] = '\0' before deleting p?
I had some code where I got a debug error when I tried to delete a not null-terminated char array, something about deleting heap memory that's not assigned. It seemed to delete memory out of the array's bounds.
|
The code:
char *p = new char[200];
p[100] = '\0';
delete[] p;
is perfectly valid C++. delete does not know or care about null-terminated strings, so your error must have had some other cause.
|
763,573
| 763,580
|
C++ / Eclipse undefined reference question
|
I'm having trouble with what is apparently a linker error ("undefined reference") in Eclipse / C++. All the classes shown below compile fine, except for one, PlayGame.cpp, which is giving the "undefined reference" error (also shown below).
Below are the relevant classes and pieces of code.
PlayerFactory.h
PlayerFactory.cpp
Game.h
Game.cpp
// constructor for game:
Game::Game (const PlayerFactory& factory)
{
cout << " constructor" << endl;
}
PlayGame.cpp
// start of code for game where error occurs
#include "Game.h"
#include "PlayerFactory.h"
int main() {
try
{
PlayerFactory factory;
Game game (factory); <== undefined reference error
...
The above line gives the error "undefined reference to `Game(PlayerFactory const&)'"
What's causing this error, and how can it be corrected?
|
The default visibility for class declarations is private. So all the member functions of both Player and PlayerFactory classes are private -- not accessible by clients. You need to make them public.
Player.h
#ifndef PLAYER_H
#define PLAYER_H
class Player
{
public:
virtual ~Player() {
cout << "Player destructor called" << endl;
}
virtual void Player::PlayerMakeMove(){
cout << "make move" << endl;
}
};
#endif // PLAYER_H
PlayerFactory.h
#ifndef PLAYERFACTORY_H
#define PLAYERFACTORY_H
class PlayerFactory
{
public:
virtual ~PlayerFactory() {
cout << "PlayerFactory destructor called" << endl;
}
virtual std::auto_ptr<Player> PlayerFactory::MakePlayerX() const{
return PlayerFactory::MakePlayer('x');
}
virtual std::auto_ptr<Player> PlayerFactory::MakePlayerO() const{
return PlayerFactory::MakePlayer('o');
}
std::auto_ptr<Player> PlayerFactory::MakePlayer (char letter) const{
auto_ptr<Player> pt( new Player() );
return pt;
}
};
#endif // PLAYERFACTORY_H
Also, the Game::Play() lacks a return statement.
Outcome Game::Play() {
cout << " play" << endl;
return PlayerXWon;
}
Do add the required headers, forward declarations and using statements as required (I skip them here).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.