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 |
|---|---|---|---|---|
2,242,966 | 2,242,989 | MIDL doesn't want me to define a HRESULT-less function! | I'm writing a custom ATL ActiveX component, but I'm having this little weeny problem: Visual Studio insists that every function defines in the *.idl file has to have a HRESULT return type, even though I want to have a ULONG return type.
[id(3), helpstring("method addh3h3")] ULONG addh3h3([in] ULONG x, [in] ULONG y);
It gives me this error:
error MIDL2269 : procedures in an object interface must return an HRESULT
So how do I go on about defining a function with a ULONG return type? My ultimate goal is to call this function of the ActiveX object from within JavaScript in a webpage.
Thank you for your time!
| Add the [local] attribute to either the interface or the method. (from http://support.microsoft.com/kb/192626).
|
2,243,786 | 2,243,792 | Initializing members with members | This is a problem I come across often. The following examples illustrates it:
struct A {
int m_SomeNumber;
};
struct B {
B( A & RequiredObject );
private:
A & m_RequiredObject;
};
struct C {
C( );
private:
A m_ObjectA;
B m_ObjectB;
};
The implementation of the constructor of C looks something like this:
C::C( )
: B( m_ObjectA )
{ }
Since the order of initialization is not defined, m_ObjectA might be uninitialized when the constructor of m_ObjectB is called, resulting in undefined behavior. One way to force a certain order of initialization would be to make the members pointers and initialize them in the constructor body, thus forcing the correct order, but this is ugly for several reasons. Is there any way to force a certain initializtion order using the initialization-list of the constructor? If not, do you have any other suggestions how to handle this.
|
Since the order of initialization is not defined
On the contrary, it is well-defined. The order of initialization is equal to the order in which the member variables are declared in your class (and that’s regardless of the actual order of the initialization list! It’s therefore a good idea to let the initialization list order match the order of the declarations to avoid nasty surprises).
|
2,243,814 | 2,253,538 | Is it possible to use different tags files for omnicomplete and general tag browsing in Vim? | I've been using ctags in Vim for years, but I've only just discovered omnicomplete. (It seems good.)
However, I have a problem: to get omnicomplete working properly I have to use the --extra=+q option when generating the tags, which is fine, but this then changes the behaviour of general tag browsing in ways that I do not like.
For example, when tab-completing tag names in Vim I don't want to tag "into" the "hierarchies" of classes - that is, when tab completing "Clas" get "ClassA, ClassA::var1, ClassA::var2, ClassB", instead of "ClassA, ClassB" - but that's what happens when using --extra=+q.
So I guess I'm after one of two things. Either:
1. The ability to disable tab-completing into "tag hierarchies" even though those hierarchies do exist in the tags file. Or,
2. The ability to use differently named tags files (ie. generated with different options) for omnicomplete and general tag browsing.
Any ideas would be much appreciated!
Cheers,
thoughton.
| OK, I think I've actually come up with an answer to my own question.
Firstly, I generate two tags files: tags_c_vim and tags_c_omni.
In my _vimrc I have:
let tags_vim='tags_c_vim'
let tags_omni='tags_c_omni'
exe "set tags=".tags_vim
to setup some variables pointing to the different tags files, and to set the "vim" tags to be the default tags.
Then I also have this, again in the _vimrc:
imap <F8> <ESC>:exe "set tags=".tags_omni<CR>a<C-X><C-O>
autocmd InsertLeave * if pumvisible() == 0|exe "set tags=".tags_vim|endif
the first line here maps F8 so it changes the tags setting to point to the "omni" tags before then invoking the omnicomplete popup menu, and the second line resets the tags setting to the "vim" tags when insert mode is next left after the popup has closed.
It's going to need some extensive use to make sure it's robust enough, but it does seem to work after some quick testing.
Two improvements I'd still like to make:
Map the setting of the "omni" tags to the omnicomplete C-X,C-O command instead of a new F8 mapping. (I think I need to set the tags and then call omni#cpp#maycomplete#Complete(), but I couldn't work out how to do this)
Hook the resetting of the "vim" tags into either omnicomplete itself finishing or the popup menu closing
Anyway, I just thought I'd share.
Cheers,
thoughton.
|
2,243,819 | 2,243,899 | Is multiple inheritance acceptable for nodes in a tree? | I was wondering:
With a tree, the root can have multiple children and no id. All nodes (except the root) have an id and the leaf nodes can not have children. It is fixed what type must be used for each depth. So the leaves are always of the same type and so are the parents of the leaves.
Since the root and the nodes can have children and only the nodes have an id I was wondering if the following use of multiple inheritance is acceptable:
class NodeWithId
{
private:
std::string m_id;
};
template<typename T>
class NodeWithChildren
{
private:
std::vector<T> m_nodes;
};
class Network: public NodeWithChildren<Subnet>
{
};
class Subnet: public NodeWithChildren<Machine>,
public NodeWithId
{
};
class Machine: public NodeWithChildren<Application>,
public NodeWithId
{
};
class Application: public NodeWithId
{
};
Or is there a better way to implement this?
edit:
removed virtual
changed classnames
|
Or is there a better way to implement this?
IMHO, your design creates classes for stuff that are best treated as object instances. At a class level I do not see the need to differentiate between Level1 nodes and Level2 nodes.
Use a design that is simple. Ask yourself, if this design has any potential benefits or not than the naive approach of having a single Node class and creating a tree structure out of Node instances (which you create at runtime).
|
2,243,953 | 2,244,996 | Memory allocation for _M_start and _M_finish in a vector | I'm defining a vector as:
vector< int, MyAlloc< int> > *v = new vector< int, MyAllooc< int> > (4);
MyAlloc is allocating space for only 4 ints. Memory for _M_start, _M_finish, and _M_end_of_storage is being allocated on the heap before the memory for the 4 ints. But who is allocating this memory for _M_start, _M_finish, and _M_end_of_storage? I want to allocate this memory myself. What do I have to do?
| When you create the vector, it allocates room for the vector's member variables (the _M ones) wherever you place the vector. If you use new, it allocates space for these variables on the heap. With local variables, the compiler makes space for them in the current stack frame. If you make the vector a member of a class, the compiler makes space for them in the containing class.
The vector then uses its allocator to allocate room for the data you wish to store in the vector, using whatever mechanism the allocator is defined to use.
|
2,244,010 | 2,244,119 | Moving C++ objects, especially stl containers, to a specific memory location | I am working with a memory manager that, on occasion, wants to defragment memory. Basically, I will go through a list of objects allocated by the memory manager and relocate them:
class A {
SomeClass* data; // This member is allocated by the special manager
};
for(... each instance of A ...)
a.data = memory_manager.relocate(a.data);
memory_manager.relocate() will memcpy() the contents of data to a new location, and return the pointer.
Although it's generally not idiomatic to memcpy() C++ classes, it seems to be a useful solution in this case, considering that I control the implementation of the (few) classes that will be used with the memory manager.
The problem is that one of those classes uses std::map, which is an opaque class as far as I am concerned. I certainly don't imagine I can memcpy() it. I may not be able to use std::map in any case. For all I know it could allocate several pieces of memory.
The best workaround I can think of is simple enough. Due to the fact that the fragmented memory manager will put new allocations at more beneficial locations, all I need to do is allocate it anew and then delete the old:
for(... each instance of A ...) {
stl::map<something>* tmp = a.the_map;
a.the_map = new stl::map<something>(tmp);
delete tmp;
}
In any case, this lead me to wonder:
Does C++ have semantics or idioms to move/copy an object into a specific memory location?
Is it possible to move the contents of an stl container to a specific memory location?
Edit: Although I didn't point it out, I would obviously pass an allocator parameter to std::map. Based on the informative answers I got, I realize the workaround I posted in my initial question would probably be the only way to reduce fragmentation. By using the map's copy constructor (and the allocator template parameter), all memory used by the map would be properly re-allocated.
As a comment pointed out, this is mostly a theoretical problem. Memory fragmentation is rarely something to worry about.
| Everytime you insert a new key,value pair the map will allocate a node to store it. The details of how this allocation takes place are determined by the allocator that the map uses.
By default when you create a map as in std::map<K,V> the default allocator is used, which creates nodes on the heap (i.e., with new/delete).
You don't want that, so you'll have to create a custom allocator class that creates nodes as dictated by your memory manager.
Creating an allocator class is not trivial. This code shows how it can be done, you'll have to adapt it to your own needs.
Once you have your allocator class (let's say you call it MemManagerAllocator) you'll have to define your map as std::map<K, V, MemManagerAllocator> and then use it like you would use a regular map.
Personally, I would need to have a really bad problem of memory fragmentation to go into all that trouble.
|
2,244,135 | 2,244,178 | Initialize array variable in structure | I ended up doing like this,
struct init
{
CHAR Name[65];
};
void main()
{
init i;
char* _Name = "Name";
int _int = 0;
while (_Name[_int] != NULL)
{
i.Name[_int] = _Name[_int];
_int++;
}
}
| Give your structure a constructor:
struct init
{
char Name[65];
init( const char * s ) {
strcpy( Name, s );
}
};
Now you can say:
init it( "fred" );
Even without a constructor, you can initialise it:
init it = { "fred" };
|
2,244,580 | 2,248,090 | Find Boost BGL vertex by a key | I am looking for a way to access vertex properties by using a key instead of vertex reference itself.
For example, if I have
class Data
{
public:
std::string name;
unsigned int value;
};
typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data > Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
instead of using
Vertex vertex1 = boost::add_vertex( g );
g[vertex1].name = "Alpha";
g[vertex1].value = 10;
I would like to have
g["Alpha"].name = "Alpha";
g["Alpha"].value = 10;
Does a ready to use mechanism exist?
| I think I have found such mechanism. It is called labeled_graph and is a part of BGL.
Instead of using adjacency_list, one can use a predefined wrapper labeled_graph:
typedef boost::labeled_graph<
boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data >,
std::string
> Graph;
After defining a graph like this, it is possible to access vertices in the following manner:
Graph g;
boost::add_vertex( "Alpha", g );
g["Alpha"].name = "Alpha";
g["Alpha"].value = 10;
boost::add_vertex( "Beta", g );
g["Beta"].name = "Beta";
g["Beta"].value = 20;
boost::add_edge_by_label( "Alpha", "Beta", g );
The side effect of this is that one need to use graph() member function to make some algorithms work:
std::vector< Graph::vertex_descriptor > container;
boost::topological_sort( g.graph(), std::back_inserter( container ) ) ;
For some reason, labeled_graph is not described in BGL documentation, but it appears in the example folder.
Thank you for reply,
Serge
|
2,244,599 | 2,247,119 | Building an FPS in OpenGL: My gun is being clipped agains the frustum | I'm building a first person shooter using OpenGL, and I'm trying to get a gun model to float in front of the camera. I've ripped a model from Fallout 3 using a resource decompiler (converted to .obj and loaded in).
However, this is what it looks like on the screen:
Half the gun's triangles are clipped to what appears to be the frustum.
I put it in front of my camera like this:
glPushMatrix();
glLoadIdentity();
glTranslatef(m_GunPos.x, m_GunPos.y, m_GunPos.z);
glRotatef(m_GunRot.x, 1, 0, 0);
glRotatef(m_GunRot.y, 0, 1, 0);
glRotatef(m_GunRot.z, 0, 0, 1);
glScalef(m_GunScale.x, m_GunScale.y, m_GunScale.z);
m_Gun->Render(NULL);
glPopMatrix();
So I save the original GL_MODELVIEW matrix, load the identity matrix, translate my gun to be slightly to the right of my camera and render it. This is my render routine for a SceneNode:
glPushMatrix();
if (m_Model) { m_Model->Render(&final); }
if (m_Children.size() > 0)
{
for (std::vector<SceneNode*>::iterator i = m_Children.begin(); i != m_Children.end(); ++i)
{
(*i)->Render(&final);
}
}
glPopMatrix();
So it renders its own model and any child SceneNode's. Finally, the actual mesh rendering looks like this:
if (m_Material)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_Material->m_TexDiffuse);
}
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vec3), &m_Vertex[0]);
glNormalPointer(GL_FLOAT, sizeof(Vec3), &m_Normal[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &m_UV[0]);
glDrawArrays(GL_TRIANGLES, 0, m_Vertex.size());
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
Is there any way to turn off clipping for just the gun? How do other games do this?
Thanks in advance.
| From the perspective (no pun intended) of OpenGL, the frustrum is just another matrix. You should be able to push the projection matrix, call gluPerspective (or glFrustrum, if you're adventurous) to set znear to a very small value, draw the gun, then pop the projection matrix and draw the rest of the scene (beware, however, that the projection matrix stack is often pretty shallow -- it can be as little as two levels).
One caveat: I've never really thought through how this should affect z-fighting. It might not do any real good -- it could work out the same as if you had the smaller znear value while drawing the whole scene.
|
2,244,863 | 2,245,025 | trying to make a simple grid-class, non-lvalue in assignment | I'm implementing a simple C++ grid class. One Function it should support is accessed through round brackets, so that I can access the elements by writing mygrid(0,0). I overloaded the () operator and i am getting the error message: "non-lvalue in assignment".
what I want to be able to do:
//main
cGrid<cA*> grid(5, 5);
grid(0,0) = new cA();
excerpt of my implementation of the grid class:
template
class cGrid
{
private:
T* data;
int mWidth;
int mHeight;
public:
cGrid(int width, int height) : mWidth(width), mHeight(height) {
data = new T[width*height];
}
~cGrid() { delete data; }
T operator ()(int x, int y)
{
if (x >= 0 && x <= mWidth) {
if (y >= 0 && y <= mHeight) {
return data[x + y * mWidth];
}
}
}
const T &operator ()(int x, int y) const
{
if (x >= 0 && x <= mWidth) {
if (y >= 0 && y <= mHeight) {
return data[x + y * mWidth];
}
}
}
The rest of the code deals with the implementation of an iterator and should not be releveant.
| As Bill remarked, the operator shouldn't be const. I believe this is the reason for the compilation error (even if the error reported seems different). The compiler only encounters the error at the assignment line because it is a template class.
To be clear, you can't have a const method return a reference to a non-const. I.e., the
problem is that the declaration T &operator... const is illegal. It should be either T &operator... or const T &operator... const. Of course you can have both.
Edit: Removing the const doesn't help because now both methods have the same signature (the return type is not considered part of the signature for purposes of resolving the call). The method being called is the one returning T, not T &. Get rid of it (or replace it with a const method returning a const reference.)
|
2,244,890 | 2,254,350 | Qt - QScrollArea widget clipping contents | I'm trying to add scrolling to a drag and drop example source that I modified. The example simply draws several draggable QLabel widgets. I was modifying it in a way that a larger number of various different length widgets would be created.
I made a class that would be called by main and would contain the scrolling widget, that in turn would contain the original widget that draws the QLabels. The only method on this class is the constructor, and here's its implementation:
layoutWidget::layoutWidget(QWidget *parent) : QWidget(parent){
QScrollArea *scroll = new QScrollArea();
QVBoxLayout *layout = new QVBoxLayout();
//widget that draws the draggable labels
Widget *w = new Widget();
scroll->setWidget(w);
scroll->setBackgroundRole(QPalette::Light);
layout->addWidget(scroll);
setLayout(layout);
}
I'm using setMinimumSize() on the Widget constructor. When I run the program, only what's inside the area defined by setMinimumSize() is drawn, the rest is clipped off. Am I missing something?
| The minimum size of the widget inside the scroll area was smaller than its content, so only what's inside that area is drawn. I used larger values for setMinimumSize() and the problem was solved.
|
2,245,100 | 2,245,227 | Dynamic programming algorithm N, K problem | An algorithm which will take two positive numbers N and K and calculate the biggest possible number we can get by transforming N into another number via removing K digits from N.
For ex, let say we have N=12345 and K=3 so the biggest possible number we can get by removing 3 digits from N is 45 (other transformations would be 12, 15, 35 but 45 is the biggest). Also you cannot change the order of the digits in N (so 54 is NOT a solution). Another example would be N=66621542 and K=3 so the solution will be 66654.
I know this is a dynamic programming related problem and I can't get any idea about solving it. I need to solve this for 2 days, so any help is appreciated. If you don't want to solve this for me you don't have to but please point me to the trick or at least some materials where i can read up more about some similar issues.
Thank you in advance.
| The trick to solving a dynamic programming problem is usually to figuring out what the structure of a solution looks like, and more specifically if it exhibits optimal substructure.
In this case, it seems to me that the optimal solution with N=12345 and K=3 would have an optimal solution to N=12345 and K=2 as part of the solution. If you can convince yourself that this holds, then you should be able to express a solution to the problem recursively. Then either implement this with memoisation or bottom-up.
|
2,245,233 | 2,245,570 | iterator_range in header file | I want to specify in a header file that the input to a function will be an iterator_range, and the iterator can be dereferenced to obtain an int. What is the best way to do this? I do not want to say iterator_range<std::vector<int>::iterator> as this binds the implementation to use std::vector<int>.
Would appreciate any ideas to specify the function the best way.
| A common way to do this is to make the range a template parameter and then let the usage you make of it be the "concept check":
template<class SinglePassRange>
void func(SinglePassRange const & nums)
{
typedef typename boost::range_iterator<SinglePassRange>::type It;
for(It it = nums.begin(), e = nums.end(); it != e; ++it)
{
int i = *it;
// Do something with your int
}
}
This won't compile if your range does not contain ints (or something convertible to int) so there's no need to add any further constraints to the interface. But if you really want you can add a concept check at the begining of your function (it will provide better error messages to your clients):
BOOST_CONCEPT_ASSERT(
(boost::Convertible<typename boost::range_value<SinglePassRange>::type,
int>));
Finally, if you don't want to make your function a template then I think that you'll have to cope with taking a boost::iterator_range<std::vector<int>::iterator> but in that case I see no advantage with respect to taking a simple std::vector&.
|
2,245,322 | 2,245,408 | how to do this in c++gui | I want to write a program for UNIX in C++ with GUI (planning it to be Qt). I haven't learned the Qt library yet btw. I want the program to be like a world map that will be divided into many cells like a grid(the grid shouldn't be visible) and when i start to ping some IP it will show me that IP location on the world map (select it like a highlight dot or something). The part for the ip discovery is finished and it successfully locates the location of the ip (via whois). Now what remains is the Gui part, which i guess is not that easy.
So i was looking for any ideas how to do the task ? Whoever had experience with similar issue - please write your suggestions and advices, or maybe some nice snippets of code.
| It actually is pretty easy. Using Qt and its GraphicsView framework. Just display a big world map and draw a dot where you want.
However, converting lon:lat coordinates to x:y needs some basic maths (you can find formulaes by googling. It will depend on the projection of your map).
Another possiblity is to use existing map tiles (like from openstreet map). Look at
http://labs.trolltech.com/blogs/2009/08/04/openstreetmap-and-qt-and-s60/
http://labs.trolltech.com/blogs/2009/07/29/maps-with-a-magnifying-glass/
Have fun!
|
2,245,330 | 2,245,459 | C++ Pass by value/reference | I have the following code snippet:
vector<DEMData>* dems = new vector<DEMData>();
ConsumeXMLFile(dems);
if(!udp_open(2500))
{
}
I want the ConsumeXMLFile method to populate the vector with DEMData objects built from reading an XML file. When ConsumeXMLFile returns, the dems vector is empty. I think I'm running into a pass by value problem.
| Are you at any point reassigning the pointer that is passed into the function? In other words, does your function look anything like this:
void ConsumeXMLFile(vector<DEMData>* dems)
{
// ... some code ...
dems = new vector<DEMData>();
// ...more code...
}
This is a common mistake that I see beginning C++ programmers (and C programmers) make. What is going on here is that a pointer to the dems vector is being passed by value, which means that if you modify the pointed-to vector, that will affect the the vector possessed by the caller. However if you modify the pointer (which is passed by value) this will not affect the pointer possessed by the caller. After the re-assignment, the dems pointer in ConsumeXMLFile will point to a totally different vector than the dems pointer that the caller holds.
One of the things that makes me suspect that you might be doing this is that this is C++ and there's no clear reason why you would want to pass a pointer to the vector instead of a reference to the vector otherwise.
|
2,245,341 | 2,245,440 | C++ / templates / GCC 4.0 bug? | Provided the code below:
template<class _ResClass, class _ResLoader=DefaultLoader>
class Resource
: public BaseResource
{
private:
_ResClass data_;
public:
explicit Resource(const std::string& path)
: data_( _ResLoader::load< _ResClass >( path ))
{ };
};
Why would it fail but this one will work?:
template<class _ResClass, class _ResLoader=DefaultLoader>
class Resource
: public BaseResource
{
private:
_ResClass data_;
public:
explicit Resource(const std::string& path)
: data_( **DefaultLoader**::load< _ResClass >( path ))
{ };
};
| load is a dependant name, so
data_( _ResLoader::template load< _ResClass >( path ))
for the same reason as typename is needed when a dependant name is a type.
|
2,245,344 | 2,245,496 | c++ fatal error c1083 project was fine before, what now? | I have a (com) c++ project, which uses a (.net) c++ dll. The project was compiling and running ok.
Now, all I did was make changes to the dll, and I'm getting a fatal error c1083- cannot open include file stdafx.h - when recompiling my (com) project.
What can this mean?
| Look for your stdafx.h. Here are the possibilities:
If it isn't missing, try restarting you machine. You could also use sysinternals' handle.exe to find out who's holding that file.
If it is missing, create it.
On the other hand, it may be possible that your project did not originally use pre-compiled headers and the option was turned on in error. So, switch off the pre-compiled header option in project properties.
|
2,245,464 | 2,272,743 | boost local_date_time math wrong? | I'm using Boost's datetime library in my project. I was very happy when I discovered that it has time duration types for hours, days, months, years, etc, and they change their value based on what you're adding them to (i.e. adding 1 month advances the month part of the date, it doesn't just add 30 days or somesuch). I thought this property held for the days type, but I decided to test it before I put it into production...
local_date_time t1(date(2010, 3, 14), hours(1), easternTime, false); // 1am on DST transition date
{
CPPUNIT_ASSERT_EQUAL(greg_year(2010), t1.local_time().date().year());
CPPUNIT_ASSERT_EQUAL(greg_month(3), t1.local_time().date().month());
CPPUNIT_ASSERT_EQUAL(greg_day(14), t1.local_time().date().day());
CPPUNIT_ASSERT_EQUAL(1L, t1.local_time().time_of_day().hours());
CPPUNIT_ASSERT_EQUAL(0L, t1.local_time().time_of_day().minutes());
CPPUNIT_ASSERT_EQUAL(0L, t1.local_time().time_of_day().seconds());
}
t1 += days(1); // the time in EST should now be 1am on the 15th
{
CPPUNIT_ASSERT_EQUAL(greg_year(2010), t1.local_time().date().year());
CPPUNIT_ASSERT_EQUAL(greg_month(3), t1.local_time().date().month());
CPPUNIT_ASSERT_EQUAL(greg_day(15), t1.local_time().date().day());
CPPUNIT_ASSERT_EQUAL(1L, t1.local_time().time_of_day().hours()); // fails, returns 2
CPPUNIT_ASSERT_EQUAL(0L, t1.local_time().time_of_day().minutes());
CPPUNIT_ASSERT_EQUAL(0L, t1.local_time().time_of_day().seconds());
}
Above you'll see my CPPUNIT unit test. It fails at the indicated line with 2, which is what I would expect if days() merely added 24 hours, instead of 1 logical day (since the DST transition causes 2010-03-14 to be 23 hours long in EST).
Am I doing something wrong? Is this a bug? Did I just completely misunderstand the design goal of the library with respect to this sort of math?
| I think the problem is in the asker's conception of what a day is. He wants it to be a 'date' day here, rather than 24 hours, but that is not a reasonable thing to ask for.
If working in local time, one is bound to encounter peculiar effects. For example, what do you expect to happen if, in a timezone that puts clocks forward from 1am to 2am, if your local time 'add date day' calculation should set the (non existent) 1.30am on the relevant Sunday morning?
A time calculation has got to move forward 24 hours - it must operate on the underlying UTC time.
To make the 'jump one day' calculation as described, work with Boost's date type, and only add in the time-of-day as the final action.
The business of being able to advance a month is quite different, because, unlike a day, a calendar month has no specific meaning as a duration. And it causes troubles too: if you advance one calendar month from 31st January, and then go back one calendar month, what date do you end up with?
|
2,245,577 | 2,245,681 | Mapping a thread number to a (non sequential) position in an array | I would like to map a thread_id. This in C/CUDA but it is more an algebraic problem that I am trying to solve.
So the mapping I am trying to achieve is along the lines:
Threads 0-15: read value array[0]
Threads 16-31: read value [3]
Threads 32-47: read value [0]
Threads 48-63: read value [3]
Threads 64-79: read value array[6]
Threads 80-95: read value array[9]
Threads 96-111: read value array[6]
Threads 112-127: read value array[9]
and so on..
Note this is a simplification of the mapping, in reality there are more than 128 threads but the sequence is as shown and threads would always map to a multiple of three.
What formula can I use that each thread can run to find out what array position it should look at?
I would like to use some kind of formula as I have in the following example and not an explicit map or any if-statements.
To illustrate how I have solved this for a different case which required a different mapping, i.e.:
Threads 0-31: read value array[0]
Threads 32-63: read value [3]
I used the code
rintf(float(tid)/96.0)*3
| This will work in C:
3 * ((n>>4 & 1) + (n>>5 & ~1))
where n is the thread number.
I made the assumption here that the pattern continues beyond 128 as: 0,3,0,3,6,9,6,9,12,15,12,15,etc.
Edit:
This form, without bitwise operations, may be easier to understand:
6 * (n/64) + 3 * ((n/16) % 2)
It will give the same results. n is assumed to be an integer, so that division will round down.
|
2,245,648 | 2,245,679 | Function argument already initialized in function declaration C++ | So here's my question in the function declaration there is an argument and it is already initialized to a certain value. What are the procedures to call this function and use that default value, or is it just a way to document code, telling other programmers what you expect them to use as a value for the parameter? Thank you.
enum File
{
XML = 0,
PDF = 1,
};
Char *SetSection(const File = XML);
| If I understand your question correctly, simply calling SetSection with no parameters will do.
SetSection();
The above call gets translated (for lack of a better term) to:
SetSection(XML);
|
2,245,664 | 2,245,983 | What is the type of string literals in C and C++? | What is the type of string literal in C? Is it char * or const char * or const char * const?
What about C++?
| In C the type of a string literal is a char[] - it's not const according to the type, but it is undefined behavior to modify the contents. Also, 2 different string literals that have the same content (or enough of the same content) might or might not share the same array elements.
From the C99 standard 6.4.5/5 "String Literals - Semantics":
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; for wide string literals, the array elements have type wchar_t, and are initialized with the sequence of wide characters...
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
In C++, "An ordinary string literal has type 'array of n const char'" (from 2.13.4/1 "String literals"). But there's a special case in the C++ standard that makes pointer to string literals convert easily to non-const-qualified pointers (4.2/2 "Array-to-pointer conversion"):
A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”.
As a side note - because arrays in C/C++ convert so readily to pointers, a string literal can often be used in a pointer context, much as any array in C/C++.
Additional editorializing: what follows is really mostly speculation on my part about the rationale for the choices the C and C++ standards made regarding string literal types. So take it with a grain of salt (but please comment if you have corrections or additional details):
I think that the C standard chose to make string literal non-const types because there was (and is) so much code that expects to be able to use non-const-qualified char pointers that point to literals. When the const qualifier got added (which if I'm not mistaken was done around ANSI standardization time, but long after K&R C had been around to accumulate a ton of existing code) if they made pointers to string literals only able to be be assigned to char const* types without a cast nearly every program in existence would have required changing. Not a good way to get a standard accepted...
I believe the change to C++ that string literals are const qualified was done mainly to support allowing a literal string to more appropriately match an overload that takes a "char const*" argument. I think that there was also a desire to close a perceived hole in the type system, but the hole was largely opened back up by the special case in array-to-pointer conversions.
Annex D of the standard indicates that the "implicit conversion from const to non-const qualification for string literals (4.2) is deprecated", but I think so much code would still break that it'll be a long time before compiler implementers or the standards committee are willing to actually pull the plug (unless some other clever technique can be devised - but then the hole would be back, wouldn't it?).
|
2,245,780 | 2,245,863 | Order of operator overload resolution involving temporaries | Consider the following minimal example:
#include <iostream>
using namespace std;
class myostream : public ostream {
public:
myostream(ostream const &other) :
ostream(other.rdbuf())
{ }
};
int main() {
cout << "hello world" << endl;
myostream s(cout);
s << "hello world" << endl;
myostream(cout) << "hello world" << endl;
}
The output, both on g++ and on Visual C++, is
hello world
hello world
0x4012a4
The version that writes to a temporary object, myostream(cout), appears to prefer the member operator ostream::operator<<(void *), instead of the free operator operator<<(ostream &, char *). It seems to make a difference whether or not the object has a name.
Why does this happen? And how do I prevent this behaviour?
Edit: Why it happens is now clear from various answers. As to how to prevent this, the following seems appealing:
class myostream : public ostream {
public:
// ...
myostream &operator<<(char const *str) {
std::operator<<(*this, str);
return *this;
}
};
However, this results in all kinds of ambiguities.
| rvalues can't be bound to non-const reference. So in your example the temporary of type ostream can't be the first argument of free operator<<(std::ostream&, char const*) and what is used is the member operator<<(void*).
If you need it, you can add a call such as
myostream(cout).flush() << "foo";
which will transform the rvalue into a reference.
Note that in C++0X, the introduction of rvalue reference will allow to provide overload of operator<< taking rvalue references as parameter, solving the root cause of the issue.
|
2,246,096 | 2,246,125 | How can I turn off ASSERT( x ) in C++? | I suspect some ASSERTION code is having side effects. I'd like to switch off ASSERT without making any other changes to how my code is compiled. I'm using MSVS2008. Switching from debug to release won't do as that will alter how memory is initialised.
| Put this at the top of your header files after the inclusions of cassert (or a include that includes cassert)
#undef assert
#define assert(x) ((void)0)
Which redefines the assert marco so that it expands to nothing.
|
2,246,104 | 2,246,282 | Auto-generating C++ code in a pre-build event using Visual Studio | I'm trying to use a pre-build event in Visual Studio (VS 2005 to be specific) to run a Python script which will automatically generate a .cpp file. The trouble I'm running into is that the compiler doesn't seem to know that this file is dirty and needs to be rebuilt until after the build has finished, which means that I need to build the solution twice -- once to generate this file, and then once more once so that this file actually gets compiled.
Without knowing much about the inner workings of the C++ compiler, my naive guess is that it makes a list of dirty files which need to be recompiled before the pre-build event runs, so it misses this auto-generated file, as it hasn't been touched until after the pre-build event.
Is there any way to inform the compiler that it needs to recompile this file if the pre-build event changes it?
| I use msvc 6.
Try...
Put the python script into the project
give it a custom build step that invokes python on it,
to create the cpp file.
Add the cpp file to your project and do a rebuild all.
This is how we do it with the Oracle Pro*C preprocessor.
It works fine.
|
2,246,220 | 2,247,624 | Debugging and killing apps on Mac OS X? | Hey all, I'm in the process of debugging a C++ app on mac os 10.5. Occasionally, I'll do something bad and cause a segfault or an otherwise illegal operation. This results in the app hanging for a while, and eventually a system dialog notifying me of the crash. The wait time between the "hang" and the dialog is significant; a few minutes. If I try to force quit the application or kill -9 it from the command line nothing happens. If I start the app from the debugger (gdb), upon a crash I get back to gdb prompt and can exit the process cleanly. That's not ideal though as gdb is slow to load.
Anyway, can you guys recommend something? Is there a way to disable the crash reporting mechanism in OS X?
Thanks.
Update 1:
Here're the zombies that are left over from an XCode execution. Apparently xcode can't stop 'em properly either.
1 eightieight@eightieights-MacBook-Pro:~$ ps auxw|grep -i Reader
2 eightieight 28639 0.0 0.0 599828 504 s004 R+ 2:54pm 0:00.00 grep -i reader
3 eightieight 28288 0.0 1.1 1049324 45032 ?? UEs 2:46pm 0:00.89 /Users/eightieight/workspace/spark/spark/reader/browser/build/Debug/Reader.app/Contents/MacOS/Reader
4 eightieight 28271 0.0 1.1 1049324 45036 ?? UEs 2:45pm 0:00.89 /Users/eightieight/workspace/spark/spark/reader/browser/build/Debug/Reader.app/Contents/MacOS/Reader
5 eightieight 28146 0.0 1.1 1049324 44996 ?? UEs 2:39pm 0:00.90 /Users/eightieight/workspace/spark/spark/reader/browser/build/Debug/Reader.app/Contents/MacOS/Reader
6 eightieight 27421 0.0 1.1 1049328 45024 ?? UEs 2:29pm 0:00.88 /Users/eightieight/workspace/spark/spark/reader/browser/build/Debug/Reader.app/Contents/MacOS/Reader
7 eightieight 27398 0.0 1.1 1049324 45044 ?? UEs 2:28pm 0:00.90 /Users/eightieight/workspace/spark/spark/reader/browser/build/Debug/Reader.app/Contents/MacOS/Reader
| There's the CrashReporterPrefs app that comes with XCode (search for it with Spotlight; should be in /Developer/Applications/Utilities). That can be to set to Server Mode to disable the application 'Unexpectedly Quit' dialog too.
Here's another suggestion:
sudo chmod 000 /System/Library/CoreServices/Problem\ Reporter.app
To re-enable, do the following:
sudo chmod 755 /System/Library/CoreServices/Problem\ Reporter.app
It might be that the application is dumping a large core file - you'd probably notice the effect on available disk space though. You can switch off core dumping using
sudo sysctl -w kern.coredump=0
Reactivate by setting =1.
|
2,246,228 | 51,732,462 | Set Range of Bits in a ushort | Lets say I have a ushort value that I would like to set bits 1 to 4 inclusive (assuming 0 is the LSB and 15 is the MSB).
In C++ you could define a struct that mapped out specific bits:
struct KibblesNBits
{
unsigned short int TheStart: 1;
unsigned short int TheMeat: 4;
unsigned short int TheRest: 11;
}
Then you could assign a value to 'TheMeat' directly. I'm looking to do something similar in C#. Ideally, I would like a funcion definition that looked like this:
public ModValue SetRange<ModValue, RangeValue>(ModValue valueToMod, int startIndex, int endIndex, RangeValue rangeValueToAssign)
It would also need to valide that the rangeValueToAssign does not exceed the maximum size (assuming values are unsigned from 0 to max). So if the range is from 1 to 4, this is 4 bits, range would be from 0 to 15. If it is outside these limits, throw an exception.
I didnt find anything in the BitConverter class that could do something like this. Best I could think of was using manaul shift operators. Is there a better way to do this?
Edit: A non generic version might look something like this:
public static ushort SetRange(ushort valueToMod, int startIndex, int endIndex, ushort rangeValueToAssign)
{
// Determine max value
ushort max_value = Convert.ToUInt16(Math.Pow(2.0, (endIndex - startIndex) + 1.0) - 1);
if(rangeValueToAssign > max_value) throw new Exception("Value To Large For Range");
// Shift the value and add it to the orignal (effect of setting range?)
ushort value_to_add = (ushort)(rangeValueToAssign << startIndex);
return (ushort)(valueToMod + value_to_add);
}
Where:
ushort new_val = SetRange(120, 1, 2, 3);
would result in 'new_val' being set to 126.
| The fixed type answers here helped me get to a generic solution as originally requested. Here's the final code (with a getter bonus).
/// <summary>Gets the bit array value from the specified range in a bit vector.</summary>
/// <typeparam name="T">The type of the bit vector. Must be of type <see cref="IConvertible"/>.</typeparam>
/// <param name="bits">The bit vector.</param>
/// <param name="startIdx">The zero-based start index of the bit range to get.</param>
/// <param name="count">The number of sequential bits to fetch starting at <paramref name="startIdx"/>.</param>
/// <returns>The value of the requested bit range.</returns>
public static T GetBits<T>(T bits, byte startIdx, byte count) where T : IConvertible
{
if (startIdx >= (Marshal.SizeOf(typeof(T)) * 8)) throw new ArgumentOutOfRangeException(nameof(startIdx));
if (count + startIdx > (Marshal.SizeOf(typeof(T)) * 8)) throw new ArgumentOutOfRangeException(nameof(count));
return (T)Convert.ChangeType((bits.ToInt64(null) >> startIdx) & ((1 << count) - 1), typeof(T));
}
/// <summary>Sets the bit values at the specified range in a bit vector.</summary>
/// <typeparam name="T">The type of the bit vector. Must be of type <see cref="IConvertible"/>.</typeparam>
/// <typeparam name="TValue">The type of the value. Must be of type <see cref="IConvertible"/>.</typeparam>
/// <param name="bits">The bit vector.</param>
/// <param name="startIdx">The zero-based start index of the bit range to set.</param>
/// <param name="count">The number of sequential bits to set starting at <paramref name="startIdx"/>.</param>
/// <param name="value">The value to set within the specified range of <paramref name="bits"/>.</param>
public static void SetBits<T, TValue>(ref T bits, byte startIdx, byte count, TValue value) where T : IConvertible where TValue : IConvertible
{
if (startIdx >= (Marshal.SizeOf(typeof(T)) * 8)) throw new ArgumentOutOfRangeException(nameof(startIdx));
if (count + startIdx > (Marshal.SizeOf(typeof(T)) * 8)) throw new ArgumentOutOfRangeException(nameof(count));
var val = value.ToInt64(null);
if (val >= (1 << count)) throw new ArgumentOutOfRangeException(nameof(value));
bits = (T)Convert.ChangeType(bits.ToInt64(null) & ~(((1 << count) - 1) << startIdx) | (val << startIdx), typeof(T));
}
|
2,246,259 | 2,246,314 | Is there a way to have a single static variable for a template class (for all types) without breaking encapsulation | I need a way to have a single static variable for all kinds of types of my template class
template <class T> class Foo { static Bar foobar;};
Well, the line above will generate a Bar object named foobar for every type T, but this is not what i want, i basically want a way to declare a variable of type Bar, so every object of type Foo has access to the same foobar variable, independent of T.
I tried to use another class to store the private stuff, but that doesnt work, because the standard does not allow stuff like template <class T> friend class Foo<T>;
So the obvious solution (shown below) is to have a global variable Bar foobar, but this obviously violates the information hiding concept (of proper encapsulation):
Bar Foo_DO_NOT_TOUCH_THIS_PLEASE_foobar;
template <class T> class Foo { static Bar& foobar;};
template <class T> Bar& Foo<T>::foobar=Foo_DO_NOT_TOUCH_THIS_PLEASE_foobar;
Ofcourse you can additionally use a detail namespace (thats what i am currently doing), but is there another way which really prohibits users from messing around with your private static variables ?
Additonally this solution will get quite messy when you have to declare lots of static methods in a similar fashion, because you will most likely have to extensivly use the friend keyword like friend RetType Foo_detail::StaticFunc(ArgT1, ArgT2).
And the users wont have a nice interface since they cant use those functions like they are used to Foo<T>::someFunc() but instead they will have to call something like Foo_static::someFunc() (if you use the namespace Foo_static for public static functions).
So is there any other solution which does not break encapsulation, and/or does not introduce lots of syntax overhead ?
EDIT:
based on all your anwsers, i tried following, and it works as intended:
typedef int Bar;
template <class T> class Foo;
class FooBase
{
static Bar foobar;
public:
template <class T> friend class Foo;
};
Bar FooBase::foobar;
template <class T> class Foo : public FooBase
{
public:
using FooBase::foobar;
};
this solution has the benefit, that users can not inherit from FooBase.
| Perhaps inherit the static member?
class OneBarForAll
{
protected:
static Bar foobar;
};
template <class T>
class Foo : public OneBarForAll
{
};
Lots of Foo<T>'s will be made, but only one OneBarForAll.
One potential problem with this is that there's nothing stopping other users of the code from inheriting from OneBarForAll and modifying foobar anyway.
Ideally you do want the template friend, as that best describes the access requirements of your design, but C++ does not currently allow that.
|
2,246,502 | 2,246,529 | C++ key input in Windows console | I'm currently developing various console games in Windows that won't really work using regular input via cin.
How can I (In a simple way using only standard windows libraries available in MSVC):
Make the program wait for a (specific?) key press and return the key ID (It would have to work for all keys including the arrow keys)
During a real-time game check for the last pressed key of the user and if there was any key pressed since the last check.
It would really help if you could include a short example program for your solution
| AFAIK you can't do it using the standard C runtime. You will need to use something such as the Win32 function GetAsyncKeyState.
|
2,246,663 | 2,246,717 | Why is the 'this' keyword not a reference type in C++ |
Possible Duplicates:
Why ‘this’ is a pointer and not a reference?
SAFE Pointer to a pointer (well reference to a reference) in C#
The this keyword in C++ gets a pointer to the object I currently am.
My question is why is the type of this a pointer type and not a reference type.
Are there any conditions under which the this keyword would be NULL?
My immediate thought would be in a static function, but Visual C++ at least is smart enough to spot this and report static member functions do not have 'this' pointers. Is this in the standard?
| See Stroustrup's Why is this not a reference
Because "this" was introduced into C++ (really into C with Classes) before references were added. Also, I chose "this" to follow Simula usage, rather than the (later) Smalltalk use of "self".
|
2,246,715 | 2,247,145 | Problems inheriting from a class in the same namespace in C++ | I was happily working in C++, until compilation time arrived.
I've got several classes inside some namespace (let's call it N); two of these classes correspond to one base class, and other derived from it. Each class has its own pair of .hpp and .cpp files; I think it'd look like:
namespace N{
class Base{
};
class Derived: public Base{
};
}
However, g++ (maybe linker) keeps telling me:
Derived.hpp:n: error: expected class-name before ‘{’ token
It doesn't recognize Base as a class, even when I have correctly #include'ed the hpp file corresponding to its definition to Derived's .hpp!
"It's something with #includes", I thought, since these classes' .hpps are #included in other files, so I added this to Derived declaration in Derived.hpp:
#include "Base.hpp"
namespace N{
class Base;
class Derived: public Base{
};
}
And now g++ complains:
Derived.hpp:n: error: invalid use of incomplete type ‘struct N::Base’
So, I got lost here. Please help me, I will apreciate it a lot. :)
(By the way, I'm rather experienced in Python, not C++, so this issues are really strange to me. Also, I changed classes' names and stuff :).
Edit: A more exact representation of my files is:
File Pieza.hpp
-----------------------
#include "Celda.hpp"
namespace Reglas
{
class Pieza
{
public:
Pieza() {}
virtual ~Pieza() {}
private:
Celda *c;
};
}
File Jugador.hpp
-----------------------
#include "Jugada.hpp"
#include "Excepciones.hpp"
#include "Pieza.hpp"
namespace Reglas
{
//compiler asked for these :S
class Celda;
class Tablero;
class Jugador : public Pieza
{
public:
Jugador() {}
virtual ~Jugador() {}
};
}
| Derived.hpp:n: error: invalid use of incomplete type ‘struct N::Base’
This makes me think that you didn't #include "Base.hpp in the Derived.cpp source file.
EDIT: In your Derived.cpp, try changing the order of #includes to:
#include "base.hpp"
#include "derived.hpp"
// .. rest of your code ..
Like this:
// Derived.hpp
#pragma once
namespace foo
{
class Base;
class Derived : public Base
{
public:
Derived();
~Derived();
};
}
// Derived.cpp
#include "base.hpp"
#include "derived.hpp"
namespace foo
{
Derived::Derived()
{
}
Derived::~Derived()
{
}
}
So, you're going to want to edit Jugador.hpp to look like this:
// Jugador.hpp
#include "Pieza.hpp" // move this above Jugada.hpp
#include "Jugada.hpp"
#include "Excepciones.hpp"
namespace Reglas
{
//compiler asked for these :S
class Celda;
class Tablero;
class Jugador : public Pieza
{
public:
Jugador() {}
virtual ~Jugador() {}
};
}
|
2,246,996 | 2,247,016 | C++ const : how come the compiler doesn't give a warning/error | Really simple question about C++ constness.
So I was reading this post, then I tried out this code:
int some_num = 5;
const int* some_num_ptr = &some_num;
How come the compiler doesn't give an error or at least a warning?
The way I read the statement above, it says:
Create a pointer that points to a constant integer
But some_num is not a constant integer--it's just an int.
| The problem is in how you're reading the code. It should actually read
Create a pointer to an integer where the value cannot be modified via the pointer
A const int* in C++ makes no guarantees that the int is constant. It is simply a tool to make it harder to modify the original value via the pointer
|
2,247,094 | 2,247,109 | What's the difference between C header files (.h) and C++ header files (.hpp)? | I noticed that the boost library uses header files of (.hpp).
I am curious since most source files I see use normal .h header files.
Could there be any special instances which warrant use of .hpp instead of .h ?
Thanks
| Just convention, nothing special. You can use any extension on include files, actually.
|
2,247,188 | 2,247,298 | Get number of bits in char | How do I get the number of bits in type char?
I know about CHAR_BIT from climits. This is described as »The macro yields the maximum value for the number of bits used to represent an object of type char.« at Dikumware's C Reference. I understand that means the number of bits in a char, doesn't it?
Can I get the same result with std::numeric_limits somehow? std::numeric_limits<char>::digits returns 7 correctly but unfortunately, because this value respects the signedness of the 8-bit char here…
| If you want to be overly specific, you can do this:
sizeof(char) * CHAR_BIT
If you know you are definitely going to do the sizeof char, it's a bit overkill as sizeof(char) is guaranteed to be 1.
But if you move to a different type such as wchar_t, that will be important.
|
2,247,270 | 2,247,446 | Access violation exception when calling a method | I've got a strange problem here. Assume that I have a class with some virtual methods. Under a certain circumstances an instance of this class should call one of those methods. Most of the time no problems occur on that stage, but sometimes it turns out that virtual method cannot be called, because the pointer to that method is NULL (as shown in VS), so memory access violation exception occurs. How could that happen?
Application is pretty large and complicated, so I don't really know what low-level steps lead to this situation. Posting raw code wouldn't be useful.
UPD: Ok, I see that my presentation of the problem is rather indefinite, so schematically code looks like
void MyClass::FirstMethod() const { /* Do stuff */ }
void MyClass::SecondMethod() const
{
// This is where exception occurs,
// description of this method during runtime in VS looks like 0x000000
FirstMethod();
}
No constructors or destructors involved.
| Heap corruption is a likely candidate. The v-table pointer in the object is vulnerable, it is usually the first field in the object. A buffer overflow for some kind of other object that happens to be adjacent to the object will wipe the v-table pointer. The call to a virtual method, often much later, will blow.
Another classic case is having a bad "this" pointer, usually NULL or a low value. That happens when the object reference on which you call the method is bad. The method will run as usual but blow up as soon as it tries to access a class member. Again, heap corruption or using a pointer that was deleted will cause this. Good luck debugging this; it is never easy.
|
2,247,289 | 2,247,348 | Best way to detect grouped words | A word is grouped if, for each letter in the word, all occurrences of that letter form exactly one consecutive sequence. In other words, no two equal letters are separated by one or more letters that are different.
Given a vector<string> return the number of grouped words.
For example :
{"ab", "aa", "aca", "ba", "bb"}
return 4.
Here, "aca" is not a grouped word.
My quick and dirty solution :
int howMany(vector <string> words) {
int ans = 0;
for (int i = 0; i < words.size(); i++) {
bool grouped = true;
for (int j = 0; j < words[i].size()-1; j++)
if (words[i][j] != words[i][j+1])
for (int k = j+1; k < words[i].size(); k++)
if (words[i][j] == words[i][k])
grouped = false;
if (grouped) ans++;
}
return ans;
}
I want a better algorithm for the same problem.
| Just considering one word, here is an O(n log n) destructive algorithm:
std::string::iterator unq_end = std::unique( word.begin(), word.end() );
std::sort( word.begin(), unq_end );
return std::unique( word.begin(), unq_end ) == unq_end;
Edit: The first call to unique reduces runs of consecutive letters to single letters. The call to sort groups identical letters together. The second call to unique checks whether sort formed any new groups of consecutive letters. If it did, then the word must not be grouped.
Advantage over the others posted is that it doesn't require storage — although that's not much of an advantage.
Here's a simple version of the alternative algo, also requiring only O(1) storage (and yes, also tested):
if ( word.empty() ) return true;
bitset<CHAR_MAX+1> symbols;
for ( string::const_iterator it = word.begin() + 1; it != word.end(); ++ it ) {
if ( it[0] == it[-1] ) continue;
if ( symbols[ it[0] ] ) return false;
symbols[ it[-1] ] = true;
}
return ! symbols[ * word.rbegin() ];
Note that you would need minor modifications to work with characters outside ASCII. bitset comes from the header <bitset>.
|
2,247,465 | 2,247,506 | Does using large libraries inherently make slower code? | I have a psychological tic which makes me reluctant to use large libraries (like GLib or Boost) in lower-level languages like C and C++. In my mind, I think:
Well, this library has thousands of
man hours put into it, and it's been
created by people who know a lot more
about the language than I ever will.
Their authors and fans say that
the libraries are fast and reliable,
and the functionality looks really
useful, and it will certainly stop me
from (badly) reinventing wheels.
But damn it, I'm never going to use
every function in that library. It's
too big and it's probably become bloated
over the years; it's another ball
and chain my program needs to drag around.
The Torvalds rant (controversial though it is) doesn't exactly put my heart at ease either.
Is there any basis to my thinking, or am I merely unreasonable and/or ignorant? Even if I only use one or two features of a large library, by linking to that library am I going to incur runtime performance overheads?
I'm sure it depends too on what the specific library is, but I'm generally interested in knowing whether large libraries will, at a technical level, inherently introduce inefficiencies.
I'm tired of obsessing and muttering and worrying about this, when I don't have the technical knowledge to know if I'm right or not.
Please put me out of my misery!
|
Even if I only use one or two features of a large library, by linking to that library am I going to incur runtime performance overheads?
In general, no.
If the library in question doesn't have a lot of position-independent code, then there will be a start-up cost while the dynamic linker performs relocations on the library when it's requested. Usually, that's part of the program's start-up. There is no run-time performance effect beyond that.
Linkers are also good at removing "dead code" from statically-linked libraries at build time, so any static libraries you use will have minimal size overhead. Performance doesn't even enter into it.
Frankly, you're worrying about the wrong things.
|
2,247,558 | 2,247,607 | find string of N 1-bits in a bit-array | As the title sais I want to find a successive run of n one-bits in a bit-array of variable size (M).
The usual use-case is N <= 8 and M <= 128
I do this operation a lot in an innerloop on an embedded device. Writing a trivial implementation is easy but not fast enough for my taste (e.g. brute force search until a solution is found).
I wonder if anyone has a more elegant solution in his bag of tricks.
| int nr = 0;
for ( int i = 0; i < M; ++i )
{
if ( bits[i] )
++nr;
else
{
nr = 0; continue;
}
if ( nr == n ) return i - nr + 1; // start position
}
What do you mean by brute force? O(M*N) or this O(M) solution? if you meant this, then I'm not sure how much more you can optimize things.
It's true we could achieve constant improvements by walking over every byte instead of every bit. This comes to mind:
When I say byte I mean a sequence of N bits this time.
for ( int i = 0; i < M; i += N )
if ( bits[i] == 0 ) // if the first bit of a byte is 0, that byte alone cannot be a solution. Neither can it be a solution in conjunction with the previous byte, so skip it.
continue;
else // if the first bit is 1, then either the current byte is a solution on its own or it is a solution in conjunction with the previous byte
{
// search the bits in the previous byte.
int nrprev = 0;
while ( i - nrprev >= 0 && bits[i - nrprev] ) ++nrprev;
// search the bits in the current byte;
int nrcurr = 0;
while ( bits[i + nrcurr + 1] && nrcurr + nrprev <= N ) ++nrcurr;
if ( nrcurr + nrprev >= N ) // solution starting at i - nrprev + 1.
return i - nrprev + 1;
}
Not tested. Might need some additional conditions to ensure correctness, but the idea seems sound.
|
2,247,567 | 2,247,694 | How might I obtain an IShellFolder from the active IShellView? | I'm trying to enhance a CFileDialog, and we're using the older version of it (the non-vista one that doesn't use IFileDialog). The older one does allow me to obtain an IShellBrowser, as well as (from that) the active IShellView.
What I cannot seem to come up with is a way to get "What IShellFolder does that IShellView refer to?"
Equally useful would be "What is the current folder that IShellBrowser has made active?"
| I think I may have solved it in a round about fashion: I'm using CDM_GETFOLDERIDLIST, which returns the current PIDL, which is all I need. :D
|
2,247,697 | 2,286,076 | Fast asymmetric cypher for C++ application | I'm looking for a fast asymmetric cypher algorithm to be used in C++ program.
Our application accesses read-only data stored in archive (custom format, somewhat similar to tar), and I would like to prevent any modifications of that archive by asymmetrically encrypting archive index (I'm aware that this isn't a perfect solution and data can still be extracted and repacked using certain techniques).
Some individual files within archive are encrypted with symmetric cypher and encryption keys for them are stored within archive index(header). Which is why I want to encrypt archive header asymmetrically.
Cypher requirements:
1) Algorithm implementation should be platform-independent.
2) Algorithm should be either easy to implement myself or it should be available in library (with source code) that allows static linking with proprietary application, which means that GPL/LGPL/viral licenses cannot be used. MIT/BSD-licensed code, or public domain code is acceptable.
3) If cypher is available in library, ideally it should have small memory footprint, and implementation should be compact. I would prefer to use a C/C++ library that implements only one cipher instead of full-blown all-purpose cipher collection.
Originally I wanted to use RSA, but it looks like it is simply too slow to be useful, and there aren't many alternatives.
So, any advice on what can I use?
| Okay, I've found what I've been looking for, and I think it is better than OpenSSL (for my purposes, at least).
There are two libraries:
libtomcrypt, which implements several cyphers (including RSA), and libtommath, that implements bignum arithmetics. Both libraries are in public domain, easy to hack/modify and have simpler programming interface than OpenSSL, and (much) better documentation than OpenSSL.
Unlike older public domain rsa code I found before, libtomcrypt can generate new keys very quickly, can import OpenSSL-generated keys, and supports padding. Another good thing about libtomcrypt is that it doesn't have extra dependencies (OpenSSL for windows wants gdi32, for example) and is smaller than OpenSSL.
I've decided to use RSA for encryption, after all, because (to me it looks like) there are no truly asymmetric alternatives. It looks like most of the other ciphers (elgamal, elliptic curves) are more suitable for symmetric encryption where session key is being encrypted asymmetrically. Which isn't suitable for me. Such ciphers are suitable for network communications/session keys, but it wouldn't be good to use that for static unchanging data on disk.
As for "RSA being slow", I've changed archive format a bit, so now only small chunk of data is being asymmetrically encrypted. Failure to decrypt this chunk will make reading archive index completely very difficult if not impossible. Also, I must admit that slowness of RSA was partially a wrong impression given by older code I've tried to use before.
Which means, question solved. Solution is RSA + libtomcrypt. RSA - because there aren't many alternatives to RSA, and libtomcrypt - because it is small and in public domain.
|
2,247,942 | 2,248,114 | Working program gets an Illegal instruction fault on 'clean machine'? | I have a program that works correctly on my development machine but produces an Illegal instruction fault when tested on a 'clean machine' where only the necessary files have been copied.
The program consists of my shared library, built from C++ sources and a C wrapper sample program that demonstrates the libraries usage. On the development machine, all are built in Eclipse w/g++ and both Debug and Release work fine. A number of standard libraries are linked in.
To test dependencies that I might have missed, I copied the .c file, my library's .so file and the library .h file to a fresh Linux install and compiled/linked them with a simple script created with the same release compile options that Eclipse is using. Both machines have g++ 4.3.2.
When I run the program on the clean machine it exits immediately after printing 'Illegal instruction'.
Running in gdb produces:
(gdb) run
Starting program: /home/sfallows/Source/Apps/MySample/MySample
[Thread debugging using libthread_db enabled]
[New Thread 0xb5c4ca90 (LWP 7063)]
Program received signal SIGILL, Illegal instruction.
[Switching to Thread 0xb5c4ca90 (LWP 7063)]
0xb7f0cb29 in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at /usr/include/c++/4.3/iostream:77
77 static ios_base::Init __ioinit;
Current language: auto; currently c++
(gdb) bt
#0 0xb7f0cb29 in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at /usr/include/c++/4.3/iostream:77
#1 0xb7f0cb48 in global constructors keyed to _ZN8NodeLockC2Ev () at ../NodeLock.cpp:194
#2 0xb7f204ad in __do_global_ctors_aux () from /home/sfallows/Source/Apps/MySample/libMyLib.so
#3 0xb7ee5c80 in _init () from /home/sfallows/Source/Apps/MySample/libMyLib.so
#4 0xb7fe1de4 in ?? () from /lib/ld-linux.so.2
#5 0x00000001 in ?? ()
#6 0xbf8e6b74 in ?? ()
#7 0xbf8e6b7c in ?? ()
#8 0x00000007 in ?? ()
#9 0xbf8e6b2c in ?? ()
#10 0x00000001 in ?? ()
#11 0x00000001 in ?? ()
#12 0xb7feeff4 in ?? () from /lib/ld-linux.so.2
#13 0x00000000 in ?? ()
(gdb) Quit
I'm not sure why it is running static construtors in NodeLock.cpp. I have neither any static/global objects in that file nor any static/global objects of that class anywhere.
The development machine is an Intel Core2 Quad and the clean machine is a Pentium 4 Dual. I assume g++ defaults to using a common subset of x86 instructions and that the processor difference is not my problem.
Any suggestions for what else to look at appreciated. I'm trying to avoid installing all of the library source and dependencies on the clean machine.
To rmn's answer and John Boker's comment: In the Windows world exes and dlls run on the plethora of Intel and AMD processors so there clearly is a widely used common subset of instructions. I thought gcc would do the same? Guess I'll fully research the instruction set/architecture options.
| You could try to compile explicitly for the i686 architecture (using -march=i686 option for gcc). Just in case you have some Core2-Specific instructions generated by the your compiler...
|
2,247,982 | 2,248,063 | c++ deque vs queue vs stack | Queue and Stack are a structures widely mentioned. However, in C++, for queue you can do it in two ways:
#include <queue>
#include <deque>
but for stack you can only do it like this
#include <stack>
My question is, what's the difference between queue and deque, why two structures proposed? For stack, any other structure could be included?
| Moron/Aryabhatta is correct, but a little more detail may be helpful.
Queue and stack are higher level containers than deque, vector, or list. By this, I mean that you can build a queue or stack out of the lower level containers.
For example:
std::stack<int, std::deque<int> > s;
std::queue<double, std::list<double> > q;
Will build a stack of ints using a deque as the underlying container and a queue of doubles using a list as the underlying container.
You can think of s as a restricted deque and q as a restricted list.
All that is necessary is that the lower level container implements the methods needed by the higher level container. These are back(), push_back(), and pop_back() for stack and front(), back(), push_back(), and pop_front() for queue.
See stack and queue for more detail.
With respect to the deque, it is much more than a queue where you can insert at both ends. In particular, it has the random access operator[]. This makes it more like a vector, but a vector where you can insert and delete at the beginning with push_front() and pop_front().
See deque for detail.
|
2,248,009 | 2,248,182 | Qt: Defining a custom event type | I have created a custom event in my Qt application by subclassing QEvent.
class MyEvent : public QEvent
{
public:
MyEvent() : QEvent((QEvent::Type)2000)) {}
~MyEvent(){}
}
In order to check for this event, I use the following code in an event() method:
if (event->type() == (QEvent::Type)2000)
{
...
}
I would like to be able to define the custom event's Type somewhere in my application so that I don't need to cast the actual integer in my event methods. So in my event() methods I'd like to be able to do something like
if (event->type() == MyEventType)
{
...
}
Any thoughts how and where in the code I might do this?
| If the event-type identifies your specific class, i'd put it there:
class MyEvent : public QEvent {
public:
static const QEvent::Type myType = static_cast<QEvent::Type>(2000);
// ...
};
// usage:
if(evt->type() == MyEvent::myType) {
// ...
}
|
2,248,038 | 2,251,372 | QWebElement manipulation of a QWebPage in a separate thread | I have a QWebPage created in the main thread (you can't create it anywhere else). I would like to manipulate this page using the QWebElement API introduced in Qt 4.6, but in a separate thread. So that thread would acquire a reference to the page and perform the necessary tree walking and attribute changes I need.
As the Threads and QObjects doc page explains, it is unsafe to manipulate QObjects in threads that don't own them unless the developer can ensure that the QObject in question will not be processing events while this manipulation is going on.
Now, this QWebPage is also being displayed in a QWebView, but the main thread will be blocked while waiting for the worker thread to finish (actually many of them, working on many different pages). Hence, the main event loop will not be running while the operation is in progress.
Thus, I believe the operation to be safe. Am I mistaken? Have I missed something? I'm basically asking for reassurance that this will not blow up in my face...
| I do think you're right, and it is safe. At least, you have me convinced :)
|
2,248,136 | 2,248,150 | set map implementation in C++ | I find that both set and map are implemented as a tree. set is a binary search tree, map is a self-balancing binary search tree, such as red-black tree? I am confused about the difference about the implementation. The difference I can image are as follow
1) element in set has only one value(key), element in map has two values.
2) set is used to store and fetch elements by itself. map is used to store and fetch elements via key.
What else are important?
| Maps and sets have almost identical behavior and it's common for the implementation to use the exact same underlying technique.
The only important difference is map doesn't use the whole value_type to compare, just the key part of it.
|
2,248,262 | 2,248,270 | Array boundaries and indexes | I had an earlier post link textwhere someone said I had my pointer initialized to the wrong element which I don't quite see why, other than they are right and it works with their correction. So here is the basic problem:
If I declare an array from 0 to 30 with
#define ENDPOINT 15
int record[2 * ENDPOINT + 1];
// and want a pointer to be at the middle of the array, so 0 is at the middle, and
// +15 is at 30, and -15 is at 0
// why is int *ptr = &record[ENDPOINT + 1] wrong? why is the correct declaration
int *ptr = &record[ENDPOINT];
Because if I put the ptr at &record[ENDPOINT], that means the 15th entry in the record array which is the 14th index, and then adding 15 would be only 29 right? Thanks!
| record[ENDPOINT] is the 16th element- the array's indices start at 0, so record[0] is the 1st element, record[1] is the 2nd element... and record[ENDPOINT] (is record[15]) is the 16th element.
You have 2*15+1 or 31 elements in your array. Adding 14 to ENDPOINT (15) yields 29, and record[29] is the 30th element in the array. record[30] would be the final, or 31st, element in the array.
|
2,248,512 | 2,251,227 | Qt build that can link statically out of the box? | I have used Qt to build a small application. It turns out that I need to reconfigure and Qt from scratch in order to be able to link statically. I've done it before, and I remember that it was a very long process.
So does anyone know a Qt SDK installer that provides the ability for static linking out of the box?
| In addition to Martin Beckett's answer.
Be careful with licenses!
If you use Qt under (L)GPL license terms and distribute your own app under (L)GPL too, than everything is OK.
Of course if you want to make proprietary software than the situation is more complicated. Very roughly, the end user should be able to (modify and) recompile Qt and use your application with the (modified and) recompiled version of the library. To achieve this with static linking, without making your source code available to the end users, it is enough to provide a linkable object code so they can re-link with their modified library.
Also if I remember correctly if you use LGPL Qt and provide source code, you don't have to use the LGPL license for your own code. You can compose your own license (if you are a lawyer =)) and deny any rights other than that the user can re-compile and re-link.
|
2,248,547 | 2,248,562 | Understanding Factories and should I use them? | I have never used Factories before for the simple reason, I don't understand when I need them. I have been working on a little game in my spare time, and I decided to implement FMOD for the sound. I looked at a wrapper designed for OpenAL(different sound setup) and it looked something like...
SoundObject*
SoundObjectManager*
SoundObjectFactory*
The SoundObject was basically the instance of each sound object. The SoundObjectManager just manages all of these objects. This is straight forward enough and makes plenty of sense, but I don't get what the factory is doing or what it is used. I have been reading up on Factorys but still don't really get them.
Any help would be appreciated!
| Think of Factory as a "virtual constructor". It lets you construct objects with a common compile time type but different runtime types. You can switch behavior simply by telling the Factory to create an instance of a different runtime type.
|
2,248,623 | 2,248,634 | C++ "dynamic" arrays | I've got some problems/misunderstandings with arrays in C++.
int myArray[30];
myArray[1]=2;
myArray[2]=4;
This is spitting out a lot of compiler errors. I don't think it is necessary to include them here as this is an easy question for everybody with experience in C(++) I guess
Why doesn't this work?
Is there a way to create a "dynamic" array that has a fixed ammount of values (so no malloc needed) but where I can change the values during runtime?
| I'm guessing you have that outside of a function.
You are allowed to define variables outside of a function. You can even call arbitrary code outside of a function provided it is part of a variable definition.
// legal outside of a function
int myArray[30];
int x = arbitrary_code();
void foo()
{
}
But you cannot have arbitrary statements or expressions outside of a function.
// ILLEGAL outside a function
myArray[1] = 5;
void foo()
{
// But legal inside a function
myArray[2] = 10;
}
|
2,248,784 | 2,248,827 | Choosing between static libs and dynamic libs/plugins? | I have been throwing stuff together in a small test game over the past 6 months or so, and right now everything is in the one project. I would like to learn more about creating an "engine" for reusability and I am trying to figure out the best way to do this.
Static Libs are obviously a tiny bit faster, as they are compiled in rather than loaded at runtime, but that really does not matter to me. The advantages of DLLs over static libs seems rather large. So im wondering what the best approach/most used approach is for a "game engine".
I am using Ogre3D (rendering engine) which supports dll plugins that it loads and what not, but I would like to write my dlls where I could basically use them anywhere. So would my best bet be to write individual DLLs for each portion of my sample engine, such as sound.dll, gui.dll, etc? Or would I be better served by creating one large dll, deemed engine.dll or something? I am assuming the best approach would be to write something like...engine.dll for the general structure, then compose it of other dlls such as sound/gui/input/etc.
Would it be silly of me to write my dlls independently of Ogre's Plugin system? My Sound relies on the FMOD library, my GUI relies on the CEGUI library, and so on. I mainly just want to create my engine to a point where it is easily usable with the functions I need from the individual librarys.
| If you are creating DLLs for re-usability it makes sense to split it up into self contained units of functions. Thus, if you have a general sound library that, for example, plays wav files, that could be separated out as sound.dll if you think lots of other programs might make use of that particular library. Likewise for anything you think would be re-usable elsewhere.
However, if it is mostly the case that the only people using your sound routines are those who will also load the rest of your game engine (or most of it) dll, I see little point in having so many separate libraries. I can see the sense in having engine.dll so that many games can be created from a single engine but not from splitting up the rest unnecessarily.
|
2,248,844 | 2,254,189 | Qt::How to lower the text in a QSpinBox | I'm using a spinbox with a custom font which looks too high in the spinbox. How do I move the text lower?
I have already reimplemented QStyle and made the font lower in another widget but I can't find where to do it with the spinbox. There must be a QRect somewhere where you can just move the top of it but I don't know and can't seem to find where it is.
| Qt specifies a QStyle::SC_SpinBoxEditField, which appears to be what you want to modify. If I recall correctly from a few years ago when I was doing stuff with styles, you should be able to hook into getting options for that subcontrol, which would include the rect within which it is supposed to be drawn. Modifying that might get the result you want. If not, it is a place to begin searching for your answer.
|
2,248,936 | 2,257,214 | Qt4: QMap causing "strict-aliasing rules" compilation error | I'm trying to create the following data structure in Qt 4.5 in C++:
QMap<int, QMap<QString, QVector<QPointF> > > animation;
However, the inclusion of this line in my code results in the following error:
cc1plus: warnings being treated as errors
In file included from XXX/XXX/XXX/MainWindow.qt.C.tmp.C:113:
/usr/lib/qt4/include/QtCore/qmap.h: In member function ‘void MainWindow::exportAnn()’:
/usr/lib/qt4/include/QtCore/qmap.h:588: error: dereferencing pointer ‘y’ does break strict-aliasing rules
/usr/lib/qt4/include/QtCore/qmap.h:586: note: initialized from here
Command exited with non-zero status 1
My organization requires me to treat all warnings as errors, so I can't simply ignore this. Is this a bug in Qt, or is there something I'm doing wrong?
| The code you mention works fine with Qt 4.6.1 and GCC 4.4.1 on Intel/Mac OS X.
$ cat a.cpp #include <QtCore>
void foo (QMap<int, QMap<QString, QVector<QPointF> > > &map)
{ map.clear(); }
$ g++-4.4-fsf -c -DQT_CORE_LIB -DQT_SHARED -I/Library/Frameworks/QtCore.framework/Versions/4/Headers a.cpp -W -Wall -Werror -g -O3 -fPIC
$
So your issue is probably fixed by upgrading to Qt 4.6.1. (Unless it's a compiler target-specific bug, which seems unlikely; plus, you haven't told us what platform you're compiling on.)
|
2,248,992 | 2,249,013 | new returns NULL when initializing static global variable in windows? | I'm working on integrating rLog with our code base, and I'm noticing a problem on Windows that I don't have on linux. In a header file I have a static variable that gives me a "verbose" logging channel (one up from debug basically), defined thusly:
static RLogChannel *rlog_verbose = DEF_CHANNEL("verbose", Log_Debug);
There's no problem with this on Linux, but on Windows I get an error as soon as the application starts.
I've tracked it down to this line in the rLog library:
RLogChannel *rlog::GetComponentChannel(const char *component, const char* path, LogLevel levl) {
...
if(!gRootChannel)
gRootChannel = new RLogChannel( "", level );
...
}
The problem is that the call to new is returning a NULL pointer, which goes unchecked
and the program promptly crashes when it's accessed. Are there rules related to allocating memory in a global context on Windows that I'm not away of?
Edit: I'm pretty sure this must be something related to the order of initialization of static objects. I wanted to be sure that I wasn't missing something obvious re: memory allocation on Windows. Thanks all!
| are you sure its returning null. It might be the whole static initializer thing. The order of static initializer invocations is not defined from file to file. If you have static code that is using rlog_verbose then gRootCHannel might well be NULL simply because the initializer hasn't been called yet.
|
2,249,018 | 2,250,268 | using setw with user-defined ostream operators | How do I make setw or something similar (boost format?) work with my user-defined ostream operators? setw only applies to the next element pushed to the stream.
For example:
cout << " approx: " << setw(10) << myX;
where myX is of type X, and I have my own
ostream& operator<<(ostream& os, const X &g) {
return os << "(" << g.a() << ", " << g.b() << ")";
}
| Just make sure that all your output is sent to the stream as part of the same call to operator<<. A straightforward way to achieve this is to use an auxiliary ostringstream object:
#include <sstream>
ostream& operator<<(ostream& os, const X & g) {
ostringstream oss;
oss << "(" << g.a() << ", " << g.b() << ")";
return os << oss.str();
}
|
2,249,108 | 2,249,281 | Can I return in void function? | I have to return to the previous level of the recursion. is the syntax like below right?
void f()
{
// some code here
//
return;
}
| Yes, you can return from a void function.
Interestingly, you can also return void from a void function. For example:
void foo()
{
return void();
}
As expected, this is the same as a plain return;. It may seem esoteric, but the reason is for template consistency:
template<class T>
T default_value()
{
return T();
}
Here, default_value returns a default-constructed object of type T, and because of the ability to return void, it works even when T = void.
|
2,249,201 | 2,249,218 | Template / Namespace Interactions | I came across a compile.. oddity? recently that led me to believe that a template, when created, is created in the same namespaces (or, at least, using the same namespaces) as where is was declared. That is;
template<class T>
class bar
{
public:
static int stuff(){return T::stuff();}
};
namespace ONE
{
struct foo
{
static int stuff(){return 1;}
};
}
namespace TWO
{
struct foo
{
static int stuff(){return 2;}
};
}
using namespace TWO;
int main()
{
return bar<foo>::stuff();
}
will return 1 when using namespace ONE and 2 when using namespace TWO.
Why? And are there other "odd" or "unexpected" interactions between namespaces and templates?
Edit: This was confusing at the time because the same templates were being used across multiple files, each using a different namespace.
| That's not unexpected. You didn't qualify which foo you wanted, so your using declaration told the compiler where to find it.
The worst template gotcha I've seen in production code had to do with non-dependent name lookup. It's pretty complicated, so it's probably best to just point you at the C++ FAQ Lite (sections 35.18-20).
|
2,249,234 | 2,249,254 | A few questions about C++ classes | I have two basic questions. The first one is about function in other classes. If I have a header file with a class in it and I want to use that function in another class I have created, do I always have to construct a class object to run a function in that class like:
someclass class; <----object construction
class.somefunction();
Is there a way just to call the function with the object construction?
And the second question is it okay to put multiple small classes in one header file?
| Functions should only be member functions if they act on an object of the class. Functions that don't act on an object should just be plain global functions (or class static):
// Global function
void foo() { /* do something */ }
// Static function
class Foo
{
public:
static void foo() { /* do something */ }
};
For your second question, yes it's ok. Generally people stick to one class per file, but in my opinion there's nothing wrong with having a few small classes in a single file.
|
2,249,395 | 2,249,403 | New .h file in Eclipse yields a #define constant | So I'm chugging along in learning C++ and I'm starting to use Eclipse. As I create my .h files, I get this strange #define constant at the top:
#ifndef CLASSNAME_H_
#define CLASSNAME_H_
#endif /* CLASSNAME_H_ */
So, what gives? Am I supposed to use CLASSNAME_H_ for something?
(I should note that "classname" is just a filler. So, for example, my latest class was Person.h and I now have PERSON_H_)
| This is a standard construct used to guard against re-inclusion of your header files, I think you are probably expected to rename CLASSNAME_H_ to something more unique.
or is your header file also called classname.h?
Edit: ok so I see now that classname wasn't the actual value, but rather an example.
In that case, NO, you shouldn't need to worry about this at all just ignore them and they will do their job.
|
2,249,571 | 2,249,580 | Acquire a lock on two mutexes and avoid deadlock | The following code contains a potential deadlock, but seems to be necessary: to safely copy data to one container from another, both containers must be locked to prevent changes from occurring in another thread.
void foo::copy(const foo & rhs)
{
pMutex->lock();
rhs.pMutex->lock();
// do copy
}
Foo has an STL container and "do copy" essentially consists of using std::copy. How do I lock both mutexes without introducing deadlock?
| Impose some kind of total order on instances of foo and always acquire their locks in either increasing or decreasing order, e.g., foo1->lock() and then foo2->lock().
Another approach is to use functional semantics and instead write a foo::clone method that creates a new instance rather than clobbering an existing one.
If your code is doing lots of locking, you may need a complex deadlock-avoidance algorithm such as the banker's algorithm.
|
2,249,587 | 2,249,739 | c++ transform with if_then_else control structure | I'm trying to change the integer values in a vector using transform and an if_then_else control structure from Boost Lambda. However my compiler is not appreciating my efforts. The code I am attempting is:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(bind(rand) % ratio == 0, _1 = bind(rand) % maxSize, _1));
I tried simplifying it to the following:
transform(theVec.begin(), theVec.end(), theVec.begin(),
if_then_else(0 == 0, _1 = MaxIntSizeCFG, _1));
but the compiler tells me: no matching function for call to 'if_then_else(..........'
I read that the return values from control structures is void, so is my attempted usage in this case entirely wrong?
Thanks in advance for your time!
| if_then_else in your usage is incorrect, in the same way this is:
int i = if (some_condition){ 0; } else { 1; };
What you want is merely the ternary operator; however, this won't work in a lambda. You can simulate this with the the if_then_else_return structure instead. (i.e., you were close!)
The if_then_else is for something like a for_each loop, where you'd take one action or the other depending on a condition. The if_then_else_return is for a ternary conditional.
|
2,249,711 | 2,249,791 | How to use the boost lexical_cast library for just for checking input | I use the boost lexical_cast library for parsing text data into numeric values quite often. In several situations however, I only need to check if values are numeric; I don't actually need or use the conversion.
So, I was thinking about writing a simple function to test if a string is a double:
template<typename T>
bool is_double(const T& s)
{
try
{
boost::lexical_cast<double>(s);
return true;
}
catch (...)
{
return false;
}
}
My question is, are there any optimizing compilers that would drop out the lexical_cast here since I never actually use the value?
Is there a better technique to use the lexical_cast library to perform input checking?
| Since the cast might throw an an exception, a compiler that would just drop that cast would be seriously broken. You can assume that all major compilers will handle this correctly.
Trying to to do the lexical_cast might not be optimal from a performance point of view, but unless you check millions of values this way it won't be anything to worry about.
|
2,249,716 | 2,249,753 | How to design a class where the user/caller has options to provide a custom behavior using a custom class | I encounters a problem where I want to have a class in which its behavior can be customized by another class, for example, Foo's constructor accepts a parameter of some type of class:
class Bar { //The default class that define behavior
};
template <typename T = Bar>
class Foo {
public:
Foo(T* t = 0) t_(t) {
if (t_ == 0) t_ = new T();
}
~Foo() {
delete t_;
}
}
Now if someone use Foo in a client code:
Foo foo;
Everything is fine. But, if we want to supply the custom class:
class Bar1 { };
Foo<Bar1> foo(new Bar1()); // This is OK
Bar1 b;
Foo<Bar1> foo(&b); // Error, b is not dynamically allocated
Is there any design pattern I can use to prevent this kind of mistakes? Or, is there any techniques or semantics where the user of Foo class can choose/specify who owns the bar object? So for example, the above Foo destructor can be like this:
~Foo() {
if (t_ is owned by this object) delete t_;
}
Bar or Bar1 or any class passed as t in Foo(T* t) might be a big object, so if it is possible I rather not to pass it by value.
Update:
What I have in mind is for the user to be able to do something like:
Foo foo(new Bar(1, 2, etc..));
//or this:
Bar bar(1, 2, etc..);
Foo foo(bar);
But if bar is a big object (for example, contains an array), then it would be inefficient to pass bar by value. The only way is to have bar passed by reference or pointer, but I also want the user to be able to use bar with parameterized constructor, and hence my confusion began.
Regarding to the auto variable scope, it would be safe if a user do something like:
int main() {
Bar1 bar1(1,2,3);
Foo foo(&bar1);
return 0;
}
As long as Foo does not delete bar1.
| You can't detect the difference between stack and heap allocation (the standard doesn't even mention a stack), but that's not the issue here.
Foo should not be deleting things that it does not own. If it wants a copy for itself then it should just make a copy:
template <class T = Bar>
class Foo
{
T t_;
public:
Foo() {}
Foo(const T& t) : t_(t) {}
};
Or if you need it to be a pointer:
template <class T = Bar>
class Foo
{
T* t_;
public:
Foo() : t_(new T()) {}
Foo(const T& t) : t_(new T(t)) {}
};
You can't just go around deleting things that people give you, and that's regardless of whether you know if it's stack or heap allocated. What if your Foo goes and deletes it but the calling code still wants to use it? Or what if that same object is passed into two of your Foo objects and they both delete it?
Your option is either to make a copy, or not delete it.
An alternative to doing the copy would be to mark whether you are using your own or someone else's:
template <class T = Bar>
class Foo
{
T* t_;
bool owned;
public:
Foo() : t_(new T()), owned(true) {}
Foo(T* t) : t_(t), owned(false) {}
~Foo() { if (owned) delete t_; }
};
In case you are wondering, t is passed by const-ref in my previous solutions, not by value, so there is no excessive expense, although there could be an expense in the copying.
|
2,250,397 | 2,250,448 | Interpretation of int (*a)[3] | When working with arrays and pointers in C, one quickly discovers that they are by no means equivalent although it might seem so at a first glance. I know about the differences in L-values and R-values. Still, recently I tried to find out the type of a pointer that I could use in conjunction with a two-dimensional array, i.e.
int foo[2][3];
int (*a)[3] = foo;
However, I just can't find out how the compiler "understands" the type definition of a in spite of the regular operator precedence rules for * and []. If instead I were to use a typedef, the problem becomes significantly simpler:
int foo[2][3];
typedef int my_t[3];
my_t *a = foo;
At the bottom line, can someone answer me the questions as to how the term int (*a)[3] is read by the compiler? int a[3] is simple, int *a[3] is simple as well. But then, why is it not int *(a[3])?
EDIT: Of course, instead of "typecast" I meant "typedef" (it was just a typo).
| First, you mean "typedef" not "typecast" in your question.
In C, a pointer to type T can point to an object of type T:
int *pi;
int i;
pi = &i;
The above is simple to understand. Now, let's make it a bit more complex. You seem to know the difference between arrays and pointers (i.e., you know that arrays are not pointers, they behave like them sometimes though). So, you should be able to understand:
int a[3];
int *pa = a;
But for completeness' sake: in the assignment, the name a is equivalent to &a[0], i.e., a pointer to the first element of the array a. If you are not sure about how and why this works, there are many answers explaining exactly when the name of an array "decays" to a pointer and when it does not:
My answer to a question titled type of an array,
Another answer with examples of instances when the name of an array does not decay to a pointer, and
The answers to what is array decaying.
I am sure there are many more such questions and answers on SO, I just mentioned some that I found from a search.
Back to the topic: when we have:
int foo[2][3];
foo is of type "array [2] of array [3] of int". This means that foo[0] is an array of 3 ints, and foo[1] is an array of 3 ints.
Now let's say we want to declare a pointer, and we want to assign that to foo[0]. That is, we want to do:
/* declare p somehow */
p = foo[0];
The above is no different in form to the int *pa = a; line, because the types of a and of foo[0] are the same. So, we need int *p; as our declaration of p.
Now, the main thing to remember about arrays is that "the rule" about array's name decaying to a pointer to its first element applies only once. If you have an array of an array, then in value contexts, the name of the array will not decay to the type "pointer to pointer", but rather to "pointer to array". Going back to foo:
/* What should be the type of q? */
q = foo;
The name foo above is a pointer to the first element of foo, i.e., we can write the above as:
q = &foo[0];
The type of foo[0] is "array [3] of int". So we need q to be a pointer to an "array [3] of int":
int (*q)[3];
The parentheses around q are needed because [] binds more tightly than * in C, so int *q[3] declares q as an array of pointers, and we want a pointer to an array. int *(q[3]) is, from above, equivalent to int *q[3], i.e., an array of 3 pointers to int.
Hope that helps. You should also read C for smarties: arrays and pointers for a really good tutorial on this topic.
About reading declarations in general: you read them "inside-out", starting with the name of the "variable" (if there is one). You go left as much as possible unless there is a [] to the immediate right, and you always honor parentheses. cdecl should be able to help you to an extent:
$ cdecl
cdecl> declare p as pointer to array 3 of int
int (*p)[3]
cdecl> explain int (*p)[3]
declare p as pointer to array 3 of int
To read
int (*a)[3];
a # "a is"
(* ) # parentheses, so precedence changes.
# "a pointer to"
[3] # "an array [3] of"
int ; # "int".
For
int *a[3];
a # "a is"
[3] # "an array [3] of"
* # can't go right, so go left.
# "pointer to"
int ; # "int".
For
char *(*(*a[])())()
a # "a is"
[] # "an array of"
* # "pointer to"
( )() # "function taking unspecified number of parameters"
(* ) # "and returning a pointer to"
() # "function"
char * # "returning pointer to char"
(Example from c-faq question 1.21. In practice, if you are reading such a complicated declaration, there is something seriously wrong with the code!)
|
2,250,408 | 2,250,432 | Getting undefined class type error but I did create the class and defined it | Im working on an assignment for one of my classes. Simply I have a GumballMachine class and a bunch of State classes that change the state of the GumballMachine.
Here is the offending code:
class GumballMachine;
class State {
public:
virtual void insertQuarter() const = 0;
virtual void ejectQuarter() const = 0;
virtual void turnCrank() const = 0;
virtual void dispense() const = 0;
protected:
GumballMachine *GBM;
};
class NoQuarterState : public State {
public:
NoQuarterState (GumballMachine *GBM) {
this->GBM = GBM;
}
void insertQuarter() const {
cout << "You inserted a quarter\n";
**this->GBM->QuarterInserted();** // <--- C2027 error on MSDN
}
};
Now further below I have defined my GumballMachine class as:
class GumballMachine {
public:
GumballMachine(int numOfGB) {
this->noQuarterState = new NoQuarterState(this);
this->soldOutState = new SoldOutState(this);
this->hasQuarterState = new HasQuarterState(this);
this->soldState = new SoldState(this);
this->winnerState = new WinnerState(this);
this->count = numOfGB;
if (0 < numOfGB) {
this->state = this->noQuarterState;
}
else {
this->state = this->soldOutState;
}
}
... more code ...
void QuarterInserted() {
this->state = this->hasQuarterState;
}
... more code ...
protected:
int count;
NoQuarterState *noQuarterState;
SoldOutState *soldOutState;
HasQuarterState *hasQuarterState;
SoldState *soldState;
WinnerState *winnerState;
State *state;
};
Visual Studios was throwing a C2259 and C2027 error but after looking at MSDN I feel like I am doing it right. Maybe I am just tired, but I can't seem to find the error/see what I did wrong.
Much thanks to any help. :D
| You cannot access any members of GumballMachine before you define the class, so you'll have to either split your file into several files, each containing one class, or define your NoQuarterState::insertQuarter method after the definition of the GumballMachine class:
class NoQuarterState : public State {
public:
NoQuarterState (GumballMachine *GBM) {
this->GBM = GBM;
}
void insertQuarter() const; // Declaration only
};
class GumballMachine {
public:
...
};
void NoQuarterState::insertQuarter() const {
cout << "You inserted a quarter\n";
this->GBM->QuarterInserted(); // Works now bec. comp. has seen the def.
}
|
2,250,650 | 2,250,919 | Encryption of Objects stored to disk using C++ (for a Java Developer) | This is two questions in one but hopefully trivial to a C++ developer.
How can I seralize an object so that I can write it to disk and retrieve it later in C++ or if this is the wrong keyword how can I write an object as a binary stream and recreate it later? Can I use inheritance to make a hierarchy of classes serializable?
what's the simplest way to encrypt / decrypt a stream of binary data given that I have an encryption key;
const vector &encryption_key
This is a proof of concept so the strength or infallibility of the encryption is less important than the code being simple and easy to explain.
I can expand on either part of the question as required, as you've probably guessed I need to persist some data to the hard disk in files and retrieve it later in another run of the application, the files are large and this is my way of caching data retrieved over the network.
Thanks,
Gav
| Boost.Serialization is probably the best option for doing this in C++. If you want to save binary data you need to create a boost::archive::binary_oarchive and associate it to your file:
std::ofstream ofs("my_file.dat");
boost::archive::binary_oarchive oarch(ofs);
Any class you want to serialize must have a member function serialize with a special signature that the library can understand. For example:
class Foo
{
int i;
Baz baz;
template<class Archive>
void serialize(Archive &ar, unsigned int version) {
ar & i;
ar & baz; // Baz must be serializable
}
};
Note that there's built-in support for versioning but that's a more advanced topic.
Saving objects of your class to the binary archive is then very easy:
Foo foo;
oarch << foo; // Serializes "foo"
The cool thing about Boost.Serialization is that same member function is used to deserialize the object. The only difference is that now you use an input archive:
std::ifstream ifs("my_file.dat");
boost::archive::binary_iarchive iarch(ofs);
Foo foo;
iarch >> foo; // Deserializes "foo"
As for the encryption part, the Botan library seems to be pretty mature an its C++ unlike OpenSSL that it's C and so a bit painful to use.
This is how I think you can do serialization + encryption under the same workflow (deserialization would be analogous):
You associate your archive to an in-memory string instead of to a file:
std::ostringstream oss;
boost::archive::binary_oarchive oarch(oss);
Everything you write to the archive will be stored in the string.
You serialize your objects like you did before:
Foo foo;
oarch << foo; // Serializes "foo" (data goes to the string)
You use the Botan library to encrypt your string. Don't take this too literally but it should be something like:
a) create a Botan memory data source associated to your string (the oss object).
b) create a Botan data sink associated to the file where you want to write ("myfile.dat").
c) create an encoder that suits your needs
d) call the encode function as in encode(source, sink);
EDIT: Changed crypto recommendantion from OpenSSL to Botan.
|
2,250,759 | 2,266,895 | How does a CRichEditCtrl know a paste operation has been performed? | It has methods like CRichEditCtrl::Copy(), CRichEditCtrl::Paste() which you can call, but I can't spot any messages the control is sent by Windows telling it to perform a paste operation. Does anyone know if such a thing exists? Or does CRichEditCtrl do something lower-level like monitoring WM_CHAR events? If so can I reuse any internal methods or would I just have to roll my own in order to override the standard paste functionality?
What I actually want is for my custom subclass (CMyRichEditCtrl : CRichEditCtrl) to ignore any formatting on text pasted in to the control. Either by getting the clipboard data in a different clipboard format, or by pasting it in as normal and immediately removing formatting on inserted text.
What I tried so far:
Checking the message for WM_PASTE in CMyRichEditCtrl::PreTranslateMessage()
Creating a method virtual void CMyRichEditCtrl::Paste()
Putting a breakpoint on CRichEditCtrl::Paste() in afxcmn.inl
Dumping every message passing through CMyRichEditCtrl::PreTranslateMessage()
Results:
1: No WM_PASTE message seen
2: It's never called
3: It's never hit... how?
4: The control never receives any WM_COMMAND, WM_PASTE or focus-related messages. Basically only mouse-move and key-press messages.
It seems other people have actually done this successfully. I'm wondering if my MFC version or something could be screwing it up, at this point.
| Handle EN_PROTECTED message.
ON_NOTIFY_REFLECT(EN_PROTECTED, &YourClass::OnProtected)
// call this from the parent class
void YourClass::Initialize()
{
CHARFORMAT format = { sizeof(CHARFORMAT) };
format.dwEffects = CFE_PROTECTED;
format.dwMask = CFM_PROTECTED;
SetDefaultCharFormat(format);
SetEventMask(ENM_PROTECTED);
}
void YourClass::OnProtected(NMHDR* pNMHDR, LRESULT* pResult)
{
*pResult = 0;
ENPROTECTED* pEP = (ENPROTECTED*)pNMHDR;
if (pEP->msg == WM_PASTE)
pResult = 1; // prevent paste
}
|
2,250,817 | 2,250,842 | function to return the windows installed drive? | i would like to know the function which returns the drive where the windows has been installed.
for example
if we run a program with following code in windows which is installed in "C:\"
temp_char = getWindowsInstalledDrive();
should return "C:\".
please point me to that function if you know. it should be a C/C++ function.
Thanks.
| You can use GetSystemDirectory(): http://msdn.microsoft.com/en-us/library/ms724373%28VS.85%29.aspx and then take the first 3 letters.
|
2,250,872 | 2,250,993 | use class and enum with same name? | I've a class and an enum value which have the same name. Inside the class I want to use the enum which gives an error. Is there any way to use the enum without renaming or moving to a different namespace?
Example:
namespace foo {
enum bar {
BAD
};
class BAD {
void worse () {
bar b = BAD; // error
}
};
};
| This is one of those tricky parts of how the name lookup is performed.
There are two identifier scopes in C++, one for class types and general identifier scope. The enum value BAD resides in the general identifier scope, while the class type BAR resides in the class identifier scope. That is the reason why you are allowed to have both an enum value and a class with the same name: both names do not collide.
Within class BAD, the identifier lookup rules will find the class BAD before it finds the enum, and thus the error. Now, if you fully qualify the identifier then the name lookup will first check the global identifier scope and match the enum value. On the opposite end, you will have to add the struct or class keyword to declare variables of type BAD.
namespace foo {
enum bad { BAD; };
class BAD {
void worse() { bad b = ::foo::BAD; } // fully qualified will match the enum
};
}
int main() {
// foo::BAD b; // error, foo::BAD is an enum, not a type
class foo::BAD b; // correct
}
Now, I would advice against this usage. It is generally not a good idea to reuse an identifier like this. Code will be more complex, and probably misleading for the casual reader (the same unqualified identifier refers to different things when used in different contexts). If the names do need to be BAD, consider using an enclosing namespace or class for either the class or the enum (prefer the enum there).
|
2,250,970 | 2,251,266 | What's the correct way to create a subclass of a MFC control? | We layout dialogs using the resource editor. So say I have a RichEditCtrl called IDC_RICH. And I want to link it to an instance of a custom class CMyRichEditCtrl : CRichEditCtrl, without losing the ability to set properties on it in resource editor.
What's the right way? You can certainly get some functionality by creating a DDX-linked variable, and changing the type to CMyRichEditCtrl. But in some cases I see people calling code like:
m_Rich.SubclassDlgItem(IDC_RICH, this));
What's the difference?
EDIT: One problem I'm seeing is that when I override Create(Ex) methods, they don't get called. It's kind of like the control is already created by the time my object gets linked to the resource identifier, pehaps?
| The windows you put on a dialog with the resource editor are created using CreateWindow(Ex) with the first argument set to the class name that is specified in the .rc file. The DDX_ mechanism then associates this instantiated window with the dialog class member in DoDataExchange().
MFC is a layer over Win32 but MFC development doesn't completely shield you from Win32. It's more like a bunch of classes and methods that take away some of the drudgery of MFC and provide some form of object-orientedness. The methods of MFC object aren't the ones that are doing the real work, and much of the framework does things under the hood and doesn't notify the 'upper layer' (i.e., MFC objects) unless that is explicitly hooked up. Create() is such a method that is only there if you want to manually create a control, it's not called by MFC when the object is created. (this is a generalization because sometimes it is, but that's outside of the scope of this discussion).
|
2,251,201 | 2,260,748 | Visual Studio as Code Browser : How to preserve the directory structure? | I've downloaded source of an opensource C++ project. It is a Linux project. As Visual Studio is my favorite IDE I want to use it to browse & study the code. I created an empty C++ project and now want to add the source code to Solution explorer.
How can I add the directory structure to "Solution Explorer". Dropping the root folder of source code on the project in solution explorer is not working. Its just adding the files to the project but directory structure is lost.
Is there any way to preserve the directory structure? I do not want to recreate the directory structure manually.
| As you didn't seem to be getting any useful answers, I thought I'd post this. I don't use VS, but two possible alternative browsing tools (both free, open source) that do respect directory structures are:
Doxygen, which will give you a browser-based hyper-linked view of your source code.
Code::Blocks a C++ IDE (to add directories and subdirectories, use the "recursive add" feature.
|
2,251,212 | 2,275,665 | How to improve Visual C++ compilation times? | I am compiling 2 C++ projects in a buildbot, on each commit. Both are around 1000 files, one is 100 kloc, the other 170 kloc. Compilation times are very different from gcc (4.4) to Visual C++ (2008).
Visual C++ compilations for one project take in the 20 minutes. They cannot take advantage of the multiple cores because a project depend on the other. In the end, a full compilation of both projects in Debug and Release, in 32 and 64 bits takes more than 2 1/2 hours.
gcc compilations for one project take in the 4 minutes. It can be parallelized on the 4 cores and takes around 1 min 10 secs. All 8 builds for 4 versions (Debug/Release, 32/64 bits) of the 2 projects are compiled in less than 10 minutes.
What is happening with Visual C++ compilation times? They are basically 5 times slower.
What is the average time that can be expected to compile a C++ kloc? Mine are 7 s/kloc with vc++ and 1.4 s/kloc with gcc.
Can anything be done to speed-up compilation times on Visual C++?
| One thing that slows down the VC++ compiler is if you have a header file that initializes concrete instances of non-trival const value types. You may see this happen with constants of type std::string or GUIDs. It affects both compilation and link time.
For a single dll, this caused a 10x slowdown. It helps if you put them in a precompiled header file, or, just declare them in a header and initialize them in a cpp file.
Do take a look into the virus scanner, and be sure to experiment with precompiled headers, without it you won't see VC++ at its best.
Oh yeah, and make sure the %TMP% folder is on the same partition as where your build is written to, as VC++ makes temp files and moves them later.
|
2,251,361 | 2,251,483 | Boost.ASIO-based HTTP client library (like libcurl) | I am looking for a modern C++ HTTP library because libcurl's shortcomings are difficult to work around by C++ wrappers. Solutions based on Boost.ASIO, which has become the de-facto C++ TCP library, are preferred.
| The other day somebody recommended this on another thread:
http://cpp-netlib.github.com/
I think this is as high-level as you will find, but I'm not sure if it's mature enough yet (I would say it probably is since they've proposed it for Boost inclusion).
|
2,251,394 | 2,251,570 | How can I use templated typedefs, that are _in_ a class, from outside the class (e.g. by another class), in relation to boost::graph | I found a very useful answer on how to create templated graphs using boost::graph under Modifying vertex properties in a Boost::Graph
For me, this is very convenient as long as I do all the work on the graph in the Graph-class itself.
However, it might be necessary to access information from outside, e.g. one might want to implement a Printer-class that takes a Graph-object and prints out all the stored information.
In that case, it could be handy to access all the vertices (e.g. by a vertex iterator). Unfortunately, this won't work, as all the typedef is done in the Graph-class and this information is not accessible from outside, so the Printer-class won't know what a vertex-iterator etc. is.
How could I address this issue and still keep the templated aspect?
Thanks.
| But the typedefs are public, so you can access them from outside:
template<typename T>
class A
{
public:
typedef T type;
typedef unsigned data;
};
Now this is the following:
A<int>::type // int
A<int>::data // unsigned
Be careful, if T is not specified
template<typename T>
void func( A<T>& a )
{
typename A<T>::type // T
typename A<T>::data // unsigned
}
|
2,251,608 | 2,251,723 | Problem inheriting member functions with similar signatures in C++ | I have an MFC C++ program that contains two classes, as follows;
struct MyStruct
{
'
'
};
class Class1
{
public:
virtual MyStruct *MyFunc(LPCTSTR x);
virtual void MyFunc(MyStruct *x);
'
'
};
class Class2 : public Class1
{
public:
virtual void MyFunc(MyStruct *x);
'
'
};
main()
{
'
'
CString Str = _T("WTF");
Class2 a;
a.MyFunc(Str);
'
'
}
When I compile this under VS2003 code I get error C2664: 'MyFunc' : cannot convert parameter 1 from 'class CString' to 'struct MyStruct *' whereas I would have expected the compiler to pick up the globally defined conversion from CString to LPCTSTR and call the base member MyStruct *MyFunc(LPCTSTR x); Note that if I remove virtual void MyFunc(MyStruct *x); from the definition of Class2 it compiles just fine.
I'm probably missing something pretty simple here, but I can't figure out why this doesn't work. Any ideas greatly appreciated.
| This is by design to handle what is called the "fragile base class" problem.
Let's assume you have classes like this:
struct A
{
void MyFunc(long) {...}
}
struct B : A
{
void MyFunc(long) { ... }
}
....
B b;
b.MyFunc(5);
Here's we would call B:MyFunc(long) because ints silently convert to longs.
But say someone later changed struct A to:
struct A
{
void MyFunc(long) {...}
void MyFunc(int) {...}
}
Now, if override worked like you assumed, that the call to b.MyFunc(5) would change to call to A::MyFunc(int) --- even though neither your calling code nor struct B, the class you are actual using, changed. This was deemed worse a little confusion.
|
2,251,635 | 58,561,767 | How to detect change of system time in Linux? | Is there a way to get notified when there is update to the system time from a time-server or due to DST change? I am after an API/system call or equivalent.
It is part of my effort to optimise generating a value for something similar to SQL NOW() to an hour granularity, without using SQL.
| You can use timerfd_create(2) to create a timer, then mark it with the TFD_TIMER_CANCEL_ON_SET option when setting it. Set it for an implausible time in the future and then block on it (with poll/select etc.) - if the system time changes then the timer will be cancelled, which you can detect.
(this is how systemd does it)
e.g.:
#include <sys/timerfd.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main(void) {
int fd = timerfd_create(CLOCK_REALTIME, 0);
timerfd_settime(fd, TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET,
&(struct itimerspec){ .it_value = { .tv_sec = INT_MAX } },
NULL);
printf("Waiting\n");
char buffer[10];
if (-1 == read(fd, &buffer, 10)) {
if (errno == ECANCELED)
printf("Timer cancelled - system clock changed\n");
else
perror("error");
}
close(fd);
return 0;
}
|
2,251,724 | 2,251,773 | error C2146: syntax error : missing ';' before identifier | i can't get rid of these errors... i have semicolons everywhere i checked...
the code is simple:
the error takes me to the definition "string name" in article.h...
main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
#include "article.h"
int main()
{
string si;
char article[128];
vector<Article> articles;
ifstream file;
file.open("input.txt",ifstream::in);
while(!file.eof())
{
file.getline(article,128);
articles.push_back(Article(article));
}
file.close();
while(1);
return(1);
}
article.h:
#ifndef Article_H
#define Article_H
class Article
{
public:
int year;
string name;
Article(char *i_name);
};
#endif
| You should add:
#include <string>
to your "article.h" header file and declare name like this:
std::string name;
|
2,252,314 | 2,252,363 | In which memory area are exception classes instances created? | I could not find the information where are exception class instances created during exception handling ? In which memory area (stack, heap, static storage, etc.) ? I assume it is not on the stack because of stack-unwinding ...
| From the standard:
15.2.4: The memory for the temporary copy of the exception being thrown is
allocated in an unspecified way,
except as noted in 3.7.3.1.
And 3.7.3.1 says:
3.7.3.1: All objects which neither have dynamic
storage duration nor are local have
static storage duration. The storage
for these objects shall last for the
duration of the program (3.6.2,
3.6.3).
|
2,252,372 | 2,252,399 | How do you make a program sleep in C++ on Win 32? | How does one "pause" a program in C++ on Win 32, and what libraries must be included?
| #include <windows.h>
Sleep(number of milliseconds);
Or if you want to pause your program while waiting for another program, use WaitForSingleObject.
|
2,252,389 | 2,253,563 | Using DirectX DLL (C++) from C# | I have a native C++ DLL using DirectX, that I want to be able to use through C# to be able to create content creation tools.
Adding COM would require quite an effort it seems.
Can P/Invoke be used to maintain classes using polymorphism, or would it require me to wrap most of the code to facilitate use of P/Invoke?
It there a better solution is available? Or should I even consider writing the tools in C++ using Qt perhaps?
| I always feel that C++/CLI is always the best option when doing C# to C++ interop. You can easily create thin wrappers for an unmanaged library that will look exactly like a managed library to your C# code. It also gives you more control over how marshaling and pinning is performed.
There are ways to automatically generate C++/CLI I believe, but I've never used them.
More info on C++/CLI here:
http://msdn.microsoft.com/en-us/magazine/cc163681.aspx
|
2,252,452 | 2,252,478 | Does a getter function need a mutex? | I have a class that is accessed from multiple threads. Both of its getter and setter functions are guarded with locks.
Are the locks for the getter functions really needed? If so, why?
class foo {
public:
void setCount (int count) {
boost::lock_guard<boost::mutex> lg(mutex_);
count_ = count;
}
int count () {
boost::lock_guard<boost::mutex> lg(mutex_); // mutex needed?
return count_;
}
private:
boost::mutex mutex_;
int count_;
};
| The only way you can get around having the lock is if you can convince yourself that the system will transfer the guarded variable atomicly in all cases. If you can't be sure of that for one reason or another, then you'll need the mutex.
For a simple type like an int, you may be able to convince yourself this is true, depending on architecture, and assuming that it's properly aligned for single-instruction transfer. For any type that's more complicated than this, you're going to have to have the lock.
|
2,252,579 | 2,253,775 | Permissions denied for directory - c++ | I'm trying to build ogre newton application from svn.
I have win7 && vs 2008.
There is inc directory which is included into resources (additional include directories).
But after compiling I get error:
fatal error C1083: Cannot open source
file: '*\newton20\inc': Permission
denied c1xx
What's wrong?
| It looks like the compiler is trying to open the inc directory as a source file.
|
2,252,745 | 2,252,787 | Entering a string of characters using arrays and pointers | Ok guys, i'm very beginner and trying to enter string to a char array using pointers..and then display what i've written.
There're two things i want to ask about. First , if i didn't want to specify a size for the array and just want it to expand to contain all string i've entered ..how is that ?
And second after i enter the string and display it...it won't contain the SPACE between word...
like if i entered "i love cookies"...it will be displayed as "ilovecookies"..So how to solve that ?
Here's my little code ...
#include <iostream>
using namespace std;
int main()
{
char *strP , str[100] ;
strP = str ;
for(int i =0 ; i<10 ; i++) cin >> *(strP+i) ;
for(int i =0 ; i<10 ; i++) cout << *(strP+i) ;
return 0;
}
sorry for my silly questions, I'm beginner to this language as said and don't want to miss things before moving on .
Thanks in advance .
| 1) You need to either use a string object or new if you want to dynamically resize your string.
2) It doesn't contain the spaces because cin reads one words at a time. There are several ways to get around this. The one I would use is switch to using scanf and printf instead of cin and cout. Or, as vivin said, you can use getchar()
EDIT: grammar
|
2,252,767 | 2,252,827 | Managing windows API differences between Windows XP and Vista/Server 2008 | I am trying to create a single executable of a simple Win32 application that has to be able to run on both Windows XP and Windows Vista/2008.
Due to some changes in the way Vista works some extra Win32 API calls have to be made to make the program function correctly as it did on XP.
Currently I detect if the application is running on a Windows version newer than XP and call the extra win32 functions as needed. This works fine when running on Vista and Server 2008 but fails when running on Windows XP.
On Windows XP when the program starts I get the error message: The procedure entry point ShutdownBlockReasonCreate could not be located in they dynamic link library USER32.DLL. This happens before any of my code starts executing and none of the code paths when running on XP should call that function.
I would really like to just have one executable that works on both XP and Vista. If possible I dont want to have to have conditional compilation and have two executables.
What is the best way to solve this issue?
| You will have to use LoadLibrary() and GetProcAddress() to get the entry point for this function. On XP you'll get a NULL back from GetProcAddress(), good enough to simply skip the call. There's a good example in the SDK docs, the only tricky part is declaring the function pointer:
typedef BOOL (WINAPI *MYPROC)(HWND, LPCWSTR);
|
2,252,793 | 2,279,194 | Is there a C++ MinMax Heap implementation? | I'm looking for algorithms like ones in the stl (push_heap, pop_heap, make_heap) except with the ability to pop both the minimum and maximum value efficiently. AKA double ended priority queue. As described here.
Any clean implementation of a double ended priority queue would also be of interest as an alternative, however this question is mainly about a MinMax Heap implementation.
My google-fu has not been fruitful, but surely, it must exist?
| If you're looking for the algorithm implementation try searching Github.
|
2,252,848 | 2,253,180 | Reading Firefox Bookmarks | Apparently, latest Firefox versions stores its bookmarks in a file called 'places.sqlite'. Like a browser can import the bookmarks from another browser, I would want to import the bookmarks to a file, but I need to know what would you need to do it?
| SQLite is an embedded, serverless, relational database. Besides the mentioned ODBC drivers, it has its own C API.
|
2,252,981 | 2,253,013 | gdb error: Unable to execute epoll_wait: (4) Interrupted system call | I am unable to run my code in debug using gdb because of the following error:
Unable to execute epoll_wait: (4) Interrupted system call
Any ideas on how to solve this?
Thanks
| You should check the epoll_wait return value, then if it's -1 compare errno to EINTR and, if so, retry the system call. This is usually done with continue in a loop.
|
2,252,996 | 2,253,337 | C++ Recursion problems <confused> | I am working on understanding recursion, and I think I have it down alright... I'm trying to build a search function (like the std::string.find()) that searches a given string for another string for example:
Given (big) string: "ru the running cat"
search (small) string: "run"
I'm trying to return a index for the where the word i am searching for (in the case above it would be **7) the recursive method i have is as follows - i can't seem to get it to return the index properly.
calling the recursive function:
index = index_of(imput.c_str(), search.c_str())
Recursion method:
int index_of( const char * i, const char * s) {
int j;
if (*s == '\0') { return; }
if (*i == '\0') {
return NULL;
}
else if ( *i == *s ) {
index_of((i++), (s++));
}
else {
j += index_of((i++), s);
}
return j;
}
another foreseeable problem is that when (like in the example - OK it sucks but i need one that worked) it reaches the "ru_" it's still stuck on the ' ' (SPACE) -> how would i get it to 'reset' the s pointer?
|
Don't change any state variables. Your code should not include the operator ++ anywhere. You are not trying to loop over a datastructure and change your local variables in some fashion - you are trying to generate an entirely new but smaller problem each time. So, all those ++ operators - whether pre or post increment - are red flags.
You have more than one sub-problem. (...so single function recursion isn't ideal).
Let's look at this systematically.
Assume you have a working index_of and you just want to call it with input that's shorter than yours, and that both haystack and needle aren't empty yet. Then one of two things may be:
The haystack starts with the same letter as the needle, and you just need to look a little deeper to verify this.
- What happens if verification succeeds - what if it fails? is this an index_of subproblem?
...or the haystack starts off wrong, and you need to look deeper.
- Is looking deeper into the haystack an index_of subproblem?
Notice that if the haystack starts OK it doesn't necessarily mean that it starts with the full search string - and if it starts OK but does not start with the full search string, you really don't need to continue looking. That means that the "starts-with" sub-problem is fundamentally different than the index-of sub-problem:
index_of: here, failure to find the search string at index 0 means you need to look further.
starts_with: here, failure to find the search string at index 0 means you need to stop.
It is possible to say startswith(haystack, needle):= 0==index_of(haystack, needle), but obviously index_of is a more complicated problem with a more expensive solution - so you shouldn't do that; it's also more confusing at first.
Identify your base cases - When either needle or haystack are empty, what does that mean?
Good names help clarify things, and recursion is hard to read at the best of times - Yacoby's reply for instance has some meaningful choices here.
Summary
I'm not going to solve your own puzzle for you, but a few tips in recap...
Avoid changing your local variables: you're trying to define a subproblem and then just call the right function for those newer, shorter parameters. Don't use side-effects, they make things terribly complex.
Recursion doesn't necessarily mean just one function A calling A - it can be any cyclic call graph that eventually terminates; you may use more functions
If needle and haystack start with the same letter, that doesn't mean that the entire needle is at the start of the haystack - and if it is not, you still need to continue searching
This line is wrong: if (*s == '\0') { return 1; }
|
2,253,168 | 2,254,183 | dynamic_cast and static_cast in C++ | I am quite confused with the dynamic_cast keyword in C++.
struct A {
virtual void f() { }
};
struct B : public A { };
struct C { };
void f () {
A a;
B b;
A* ap = &b;
B* b1 = dynamic_cast<B*> (&a); // NULL, because 'a' is not a 'B'
B* b2 = dynamic_cast<B*> (ap); // 'b'
C* c = dynamic_cast<C*> (ap); // NULL.
A& ar = dynamic_cast<A&> (*ap); // Ok.
B& br = dynamic_cast<B&> (*ap); // Ok.
C& cr = dynamic_cast<C&> (*ap); // std::bad_cast
}
the definition says:
The dynamic_cast keyword casts a datum from one pointer or reference
type to another, performing a runtime check to ensure the validity of the cast
Can we write an equivalent of dynamic_cast of C++ in C so that I could better understand things?
| Here's a rundown on static_cast<> and dynamic_cast<> specifically as they pertain to pointers. This is just a 101-level rundown, it does not cover all the intricacies.
static_cast< Type* >(ptr)
This takes the pointer in ptr and tries to safely cast it to a pointer of type Type*. This cast is done at compile time. It will only perform the cast if the types are related. If the types are not related, you will get a compiler error. For example:
class B {};
class D : public B {};
class X {};
int main()
{
D* d = new D;
B* b = static_cast<B*>(d); // this works
X* x = static_cast<X*>(d); // ERROR - Won't compile
return 0;
}
dynamic_cast< Type* >(ptr)
This again tries to take the pointer in ptr and safely cast it to a pointer of type Type*. But this cast is executed at runtime, not compile time. Because this is a run-time cast, it is useful especially when combined with polymorphic classes. In fact, in certain cases the classes must be polymorphic in order for the cast to be legal.
Casts can go in one of two directions: from base to derived (B2D) or from derived to base (D2B). It's simple enough to see how D2B casts would work at runtime. Either ptr was derived from Type or it wasn't. In the case of D2B dynamic_cast<>s, the rules are simple. You can try to cast anything to anything else, and if ptr was in fact derived from Type, you'll get a Type* pointer back from dynamic_cast. Otherwise, you'll get a NULL pointer.
But B2D casts are a little more complicated. Consider the following code:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void DoIt() = 0; // pure virtual
virtual ~Base() {};
};
class Foo : public Base
{
public:
virtual void DoIt() { cout << "Foo"; };
void FooIt() { cout << "Fooing It..."; }
};
class Bar : public Base
{
public :
virtual void DoIt() { cout << "Bar"; }
void BarIt() { cout << "baring It..."; }
};
Base* CreateRandom()
{
if( (rand()%2) == 0 )
return new Foo;
else
return new Bar;
}
int main()
{
for( int n = 0; n < 10; ++n )
{
Base* base = CreateRandom();
base->DoIt();
Bar* bar = (Bar*)base;
bar->BarIt();
}
return 0;
}
main() can't tell what kind of object CreateRandom() will return, so the C-style cast Bar* bar = (Bar*)base; is decidedly not type-safe. How could you fix this? One way would be to add a function like bool AreYouABar() const = 0; to the base class and return true from Bar and false from Foo. But there is another way: use dynamic_cast<>:
int main()
{
for( int n = 0; n < 10; ++n )
{
Base* base = CreateRandom();
base->DoIt();
Bar* bar = dynamic_cast<Bar*>(base);
Foo* foo = dynamic_cast<Foo*>(base);
if( bar )
bar->BarIt();
if( foo )
foo->FooIt();
}
return 0;
}
The casts execute at runtime, and work by querying the object (no need to worry about how for now), asking it if it the type we're looking for. If it is, dynamic_cast<Type*> returns a pointer; otherwise it returns NULL.
In order for this base-to-derived casting to work using dynamic_cast<>, Base, Foo and Bar must be what the Standard calls polymorphic types. In order to be a polymorphic type, your class must have at least one virtual function. If your classes are not polymorphic types, the base-to-derived use of dynamic_cast will not compile. Example:
class Base {};
class Der : public Base {};
int main()
{
Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // ERROR - Won't compile
return 0;
}
Adding a virtual function to base, such as a virtual dtor, will make both Base and Der polymorphic types:
class Base
{
public:
virtual ~Base(){};
};
class Der : public Base {};
int main()
{
Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // OK
return 0;
}
|
2,253,362 | 2,253,669 | How to install Microsoft.VisualStudio.Shell.dll on Client Computer | I am dealing with some code that won't install on client machines (NOT running Visual Studio) because is makes reference to VSConstants.S_OK, which is in Microsoft.VisualStudio.Shell.dll. Is there a redistributable that includes this, or do I need to have the code updated to use a different constant.
| Microsoft.VisualStudio.Shell.dll is parenthetically not a redistributable component. You'll find a list of the ones you can redistribute in the redist.txt file in the Visual Studio install directory.
Getting rid of this particular dependency isn't hard. It is a COM HRESULT value, S_OK = 0. You can find those values listed in the WinError.h SDK header file. For VS2008, you'll find it in the c:\program files\microsoft sdks\windows\v6.0a\include. Earlier releases in the vc\PlatformSDK subdirectory of the VS install directory.
|
2,253,484 | 2,253,523 | Ideas for specific data structure in c++ | I need to do some task.
There are numbers give in two rows and they act like pairs of integers (a, b). I have to find the maximum 5 numbers of the a-row and then select the max of those 5 but this time from the b-row. Ex:
1 4
5 2
3 3
7 5
6 6
2 9
3 1
In this example, the pair i need is (6,6) because 6 (a) is in the top 5 of the a[i] numbers and 6 (b) is the maximum in the b section of those 5 pairs.
I was thinking of doing this with vectors and my own defined structures, also use some temp arrays but i don't know if that's the right thing to do maybe there is simpler way to do this.
Any ideas ?
EDIT: I also need the index number of the pair (in the case that is 5, it's the fifth pair i.e).
| A priority queue holding pairs that does its order evaluations based on the first element of the pair would be appropriate. You could insert all the pairs and then extract the top 5. Then just iterate on that list of pairs looking for the max of the second element of each pair.
edit
I should say that it is a decent solution only if you can accept a runtime on the order of O(n * lg n)
|
2,253,690 | 2,253,742 | What makes STL fast? | If one implements an array class the way it is commonly implemented, its performance is slower compared to its STL equivalent like a vector. So what makes STL containers/algorithms fast?
| STL algorithms like for_each take function objects that can be easily inlined. C, on the other hand, uses function pointers which are much more difficult for the compiler to optimize.
This makes a big difference in some algorithms like sorting in which the comparer function must be called many times.
Wikipedia has some more information in case you are interested.
EDIT:
As for the STL's vector class, I don't think it's necessarily faster that what you could find in, say, glibc.
|
2,253,725 | 2,285,135 | How can I work around the GetParent/EnumChildWindows asymmetry? | I recently inspect a GUI with Microsoft's Spy++ and noticed a strange structure; it looked like this (warning, ASCII art ahead):
|
+ 002004D6 "MyRootWindow1" FooClassName
| |
| + 001F052C "MyChildWindow" ClassOfChildWindow
|
\ 001D0A8C "MyRootWindow2" SomeOtherClassName
There are two root windows, 002004D6 and 001D0A8c, the former one of which has one child window, 001F052C.
Now, this would be all good and find if it wasn't for one thing: calling GetParent (or watching the 'Parent Window' or 'Owner Window' fields in Spy++) on the child window (001F052C) yields 001D0A8C.
Read: "MyChildWindow" is a child of "MyRootWindow1", but "MyRootWindow1" is not the parent of "MyChildWindow". Instead, the parent of "MyChildWindow" is "MyRootWindow2" - but, to make this complete, enumerating the children of "MyRootWindow2" does not yield "MyChildWindow".
This is a perfectly static GUI applications, so there are no race conditions here or anything.
Does anybody know how this can happen? Does anybody know how I can work around this? Until
now, I used GetParent and EnumChildWindows to get the parent (or children) for a given HWND, and I assumed that this relationship is symmetrical. Is there maybe something else I should be using?
EDIT: Here's the code for a small C++ program which demonstrates the problem:
const HINSTANCE thisModule = ::GetModuleHandle( NULL );
HWND oldParent = ::CreateWindow( TEXT("STATIC"),
TEXT("Old parent"),
WS_VISIBLE | WS_BORDER,
0, 0, 850, 500,
NULL,
NULL,
thisModule,
NULL );
HWND child = ::CreateWindow( TEXT("STATIC"),
TEXT("This is a sample dialog"),
WS_OVERLAPPED | WS_POPUP | WS_VISIBLE | WS_BORDER,
100, 100, 300, 300,
oldParent,
NULL,
thisModule,
NULL );
HWND newParent = ::CreateWindow( TEXT("STATIC"),
TEXT("Fake main window"),
WS_VISIBLE | WS_BORDER,
0, 0, 850, 500,
NULL,
NULL,
thisModule,
NULL );
::SetParent( child, newParent );
Note how the 'child' object has WS_POPUP and WS_OVERLAPPED set, but not WS_CHILD.
| The documentation for GetParent explains:
"Note that, despite its name, this function can return an owner window instead of a parent window. "
As you are not creating a child window i'm guessing you hit this case.
You should be able to call GetAncestor passing GA_PARENT as the documentation says:
"Retrieves the parent window. This does not include the owner, as it does with the GetParent function."
See Win32 window Owner vs window Parent?
|
2,253,738 | 2,253,818 | C++ typedef interpretation of const pointers | Firstly, sample codes:
Case 1:
typedef char* CHARS;
typedef CHARS const CPTR; // constant pointer to chars
Textually replacing CHARS becomes:
typedef char* const CPTR; // still a constant pointer to chars
Case 2:
typedef char* CHARS;
typedef const CHARS CPTR; // constant pointer to chars
Textually replacing CHARS becomes:
typedef const char* CPTR; // pointer to constant chars
In case 2, after textually replacing CHARS, the meaning of the typedef changed. Why is this so? How does C++ interpret this definition?
| There's no point in analyzing typedef behavior on the basis of textual replacement. Typedef-names are not macros, they are not replaced textually.
As you noted yourself
typedef CHARS const CPTR;
is the same thing as
typedef const CHARS CPTR;
This is so for the very same reason why
typedef const int CI;
has the same meaning as
typedef int const CI;
Typedef-name don't define new types (only aliases to existing ones), but they are "atomic" in a sense that any qualifiers (like const) apply at the very top level, i.e. they apply to the entire type hidden behind the typedef-name. Once you defined a typedef-name, you can't "inject" a qualifier into it so that it would modify any deeper levels of the type.
|
2,253,825 | 2,253,858 | C++ std::string InputIterator code to C code | I have some C++ code that I found that does exactly what I need, however I need it in C and I do not know how I could do it in C, so I am hoping someone can help me out.
The C++ code is:
std::string value( (const char *)valueBegin, (const char *)valueEnd );
This is using the string::string constructor:
template<class InputIterator> string (InputIterator begin, InputIterator end);
Can anyone help me in converting this to C code?
Thanks!
| // Get the number of characters in the range
size_t length = valueEnd - valueBegin;
// Allocate one more for the C style terminating 0
char *data = malloc(length + 1);
// Copy just the number of bytes requested
strncpy(data, valueBegin, length);
// Manually add the C terminating 0
data[length] = '\0';
|
2,253,878 | 12,785,369 | Why does C++ disallow anonymous structs? | Some C++ compilers permit anonymous unions and structs as an extension to standard C++. It's a bit of syntactic sugar that's occasionally very helpful.
What's the rationale that prevents this from being part of the standard? Is there a technical roadblock? A philosophical one? Or just not enough of a need to justify it?
Here's a sample of what I'm talking about:
struct vector3 {
union {
struct {
float x;
float y;
float z;
};
float v[3];
};
};
My compiler will accept this, but it warns that "nameless struct/union" is a non-standard extension to C++.
| As others have pointed out anonymous unions are permitted in standard C++, but anonymous structs are not.
The reason for this is that C supports anonymous unions but not anonymous structs*, so C++ supports the former for compatibility but not the latter because it's not needed for compatibility.
Furthermore, there's not much use to anonymous structs in C++. The use you demonstrate, to have a struct containing three floats which can be referred to either by .v[i], or .x, .y, and .z, I believe results in undefined behavior in C++. C++ does not allow you to write to one member of a union, say .v[1], and then read from another member, say .y. Although code that does this is not uncommon it is not actually well defined.
C++'s facilities for user-defined types provide alternative solutions. For example:
struct vector3 {
float v[3];
float &operator[] (int i) { return v[i]; }
float &x() { return v[0]; }
float &y() { return v[1]; }
float &z() { return v[2]; }
};
* C11 apparently adds anonymous structs, so a future revision to C++ may add them.
|
2,253,950 | 2,254,056 | Unit Testing Private Method in Resource Managing Class (C++) | I previously asked this question under another name but deleted it because I didn't explain it very well.
Let's say I have a class which manages a file. Let's say that this class treats the file as having a specific file format, and contains methods to perform operations on this file:
class Foo {
std::wstring fileName_;
public:
Foo(const std::wstring& fileName) : fileName_(fileName)
{
//Construct a Foo here.
};
int getChecksum()
{
//Open the file and read some part of it
//Long method to figure out what checksum it is.
//Return the checksum.
}
};
Let's say I'd like to be able to unit test the part of this class that calculates the checksum. Unit testing the parts of the class that load in the file and such is impractical, because to test every part of the getChecksum() method I might need to construct 40 or 50 files!
Now lets say I'd like to reuse the checksum method elsewhere in the class. I extract the method so that it now looks like this:
class Foo {
std::wstring fileName_;
static int calculateChecksum(const std::vector<unsigned char> &fileBytes)
{
//Long method to figure out what checksum it is.
}
public:
Foo(const std::wstring& fileName) : fileName_(fileName)
{
//Construct a Foo here.
};
int getChecksum()
{
//Open the file and read some part of it
return calculateChecksum( something );
}
void modifyThisFileSomehow()
{
//Perform modification
int newChecksum = calculateChecksum( something );
//Apply the newChecksum to the file
}
};
Now I'd like to unit test the calculateChecksum() method because it's easy to test and complicated, and I don't care about unit testing getChecksum() because it's simple and very difficult to test. But I can't test calculateChecksum() directly because it is private.
Does anyone know of a solution to this problem?
| Basically, it sounds like you want a mock to make unit testing more feasible. The way you make a class targetable for unit testing independantly of the object hierarchy and of external dependencies is through dependency injection. Create a class "FooFileReader" like so:
class FooFileReader
{
public:
virtual std::ostream& GetFileStream() = 0;
};
Make two implementations, one that opens a file and exposes it as a stream (or an array of bytes if that is what you really need.) The other is a mock object that just returns test data designed to stress your algorithm.
Now, make the foo constructor have this signature:
Foo(FooFileReader* pReader)
Now, you can construct foo for unit testing by passing a mock object, or construct it with a real file using the implementation that opens the file. Wrap construction of the "real" Foo in a factory to make it simpler for clients to get the correct implementation.
By using this approach, there's no reason not to test against " int getChecksum()" since its implementation will now use the mock object.
|
2,253,969 | 2,254,057 | Proper vector memory management | I'm making a game and I have a vector of bullets flying around. When the bullet is finished, I do bullets.erase(bullets.begin() + i); Then the bullet disappears. However it does notseem to get rod of the memory. If I create 5000 bullets then create 5,000 more after those die off, memory stays the same, but if I create 5,000 more while those 5000 are flying, it will allocate new space. What do I have to do to actually free up this memory?
| The std::vector class automatically manages its internal memory. It will expand to hold as many items as you put into it, but in general it will not shrink on its own as you remove items (although it will of course release the memory when it destructs).
The std::vector has two relevant concepts of "size". First is the "reserved" size, which is how much memory it has allocated from the system to use for storing vector elements. The second is the "used" size, which is how many elements are logically in the vector. Clearly, the reserved size must be at least as large as the used size. You can discover the used size with the size() method (which I'm sure you already know), and you can discover the reserved size using the capacity() method.
Usually, when the used and reserved sizes are the same, and you try to insert a new element, the vector will allocate a new internal buffer of twice the previous reserved size, and copy all of the existing elements into that buffer. This is transparent to you except that it will invalidate any iterators that you are holding. As I noted before, AFAIK, most STL implementations will never shrink the reserved size as a response to an erasure.
Unfortunately, while you can force a vector to increase its reserved size using the reserve() method, this does not work for decreasing the reserved capacity. As far as I can tell, your best bet for effecting a reduction in capacity is to do the following:
std::vector<Bullet>(myVector).swap(myVector);
What this will do is create a temporary vector which is a copy of the original vector (but with the minimum necessary capacity), and then swap the internal buffers of the two vectors. This will cause your original vector to have the same data but a potentially smaller reserved size.
Now, because creating that temporary copy is a relatively expensive operation (i.e. it takes a lot more processor time than normal reads/insertions/deletions), you don't want to do it every time you erase an element. For the same reason, this is why the vector doubles its reserved size rather than increasing it by 1 when you need to exceed the existing size. Therefore, what I would recommend is that after you have erased a relatively large number of elements, and you know you will not be adding that many more any time soon, perform the swap 'trick' above to reduce the capacity.
Finally, you may also want to consider using something other than a std::vector for this. Erasing elements from the middle of a vector, which it seems that you are doing frequently, is a slow operation compared to many other types of data structures (since the vector has to copy all of the subsequent elements back one slot to fill the hole). Which data structure is best for your purposes depends on what else you are doing with the data.
|
2,254,263 | 2,254,306 | Order of member constructor and destructor calls | Oh C++ gurus, I seek thy wisdom. Speak standardese to me and tell my if C++ guarantees that the following program:
#include <iostream>
using namespace std;
struct A
{
A() { cout << "A::A" << endl; }
~A() { cout << "A::~" << endl; }
};
struct B
{
B() { cout << "B::B" << endl; }
~B() { cout << "B::~" << endl; }
};
struct C
{
C() { cout << "C::C" << endl; }
~C() { cout << "C::~" << endl; }
};
struct Aggregate
{
A a;
B b;
C c;
};
int main()
{
Aggregate a;
return 0;
}
will always produce
A::A
B::B
C::C
C::~
B::~
A::~
In other words, are members guaranteed to be initialized by order of declaration and destroyed in reverse order?
|
In other words, are members guaranteed to be initialized by order of declaration and destroyed in reverse order?
Yes to both. See 12.6.2
6 Initialization shall proceed in the
following order:
First, and only for
the constructor of the most derived
class as described below, virtual base
classes shall be initialized in the
order they appear on a depth-first
left-to-right traversal of the
directed acyclic graph of base
classes, where “left-to-right” is the
order of appearance of the base class
names in the derived class
base-specifier-list.
Then, direct
base classes shall be initialized in
declaration order as they appear in
the base-specifier-list (regardless of
the order of the mem-initializers).
Then, non-static data members shall be
initialized in the order they were
declared in the class definition
(again regardless of the order of the
mem-initializers).
Finally, the
compound-statement of the constructor
body is executed. [ Note: the
declaration order is mandated to
ensure that base and member subobjects
are destroyed in the reverse order of
initialization. —end note ]
|
2,254,293 | 2,254,367 | Drawing real coordinates | I've implemented a plotting class that is currently capable of handling integer values only. I would like to get advice about techniques/mechanisms in order to handle floating numbers. Library used is GDI.
Thanks,
Adi
| At some point, they need to be converted to integers to draw actual pixels.
Generally speaking, however, you do not want to just cast each float to int, and draw -- you'll almost certainly get a mess. Instead, you need/want to scale the floats, then round the scaled value to an integer. In most cases, you'll want to make the scaling factor variable so the user can zoom in and out as needed.
Another possibility is to let the hardware handle most of the work -- you could use OpenGL (for one example) to render your points, leaving them as floating point internally, and letting the driver/hardware handle issues like scaling and conversion to integers. This has a rather steep cost up-front (learning enough OpenGL to get it to do anything useful), but can have a fairly substantial payoff as well, such as fast, hardware-based rendering, and making it relatively easy to handle some things like scaling and (if you ever need it) being able to display 3D points as easily as 2D.
Edit:(mostly response to comment): Ultimately it comes down to this: the resolution of a screen is lower than the resolution of a floating point number. For example, a really high resolution screen might display 2048 pixels horizontally -- that's 11 bits of resolution. Even a single precision floating point number has around 24 bits of precision. No matter how you do it, reducing 24-bit resolution to 12-bit resolution is going to lose something -- usually a lot.
That's why you pretty nearly have to make your scaling factor variable -- so the user can choose whether to zoom out and see the whole picture with reduced resolution, or zoom in to see a small part at high resolution.
Since sub-pixel resolution was mentioned: it does help, but only a little. It's not going to resolve a thousand different items that map to a single pixel.
|
2,254,329 | 2,254,394 | How to port C++ to swf with Alchemy? | Alchemy allows users to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). While this idea seems really promising has anyone had success with this - if so are there examples?
I was wanting to convert some old DOS programs to SWF so they could be ran in the browser.
| Most old DOS code isn't very portable, so running it on anything but DOS will take considerable work. Quite a bit of it makes direct use of DOS interrupts, absolute locations in the memory map, and so on. Getting these to run under AVM2 would basically not just require a C compiler, but a full emulation of MS-DOS, a BIOS, and PC hardware.
|
2,254,536 | 2,254,556 | bridge pattern vs. decorator pattern | Can anybody elaborate the Bridge design pattern and the Decorator pattern for me. I found it similar in some way. I don't know how to distinguish it?
My understanding is that in Bridge, it separate the implementation from the interface, generally you can only apply one implementation. Decorator is kind of wrapper, you can wrap as many as you can.
For example,
Bridge pattern
class Cellphone {
private:
Impl* m_OS; // a cellphone can have different OS
}
Decorator pattern
class Shirt {
private:
Person * m_p; //put a shirt on the person;
}
| The Decorator should match the interface of the object you're decorating. i.e. it has the same methods, and permits interception of the arguments on the way in, and of the result on the way out. You can use this to provide additional behaviour to the decorated object whilst maintaining the same interface/contract. Note that the interface of the Decorator can provide additional functionality to create a more useful object.
The Bridge has no such constraint. The client-facing interface can be different from the underlying component providing the implementation, and thus it bridges between the client's interface, and the actual implementation (which may not be client-friendly, subject to change etc.)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.