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
|
|---|---|---|---|---|
351,806
| 351,894
|
Where is the Don't Fragment Bit of the IP Flags used?
|
I am curious to know where the "Don't Fragment" [DF] Bit of the IP Flags is used. As fragmentation is invisible to higher layers and they don't care too.
I am also looking for an example.
Thanks a lot in advance.
|
Fragmentation is not always invisible to all upper layers. Some early (and probably even current) micro-controller TCP/IP stacks did not implement the full capabilities such as fragmentation handling. Use of the flag in that situation would ensure that the packet arrived in its original form instead of a lot of fragments which the other end couldn't handle.
In addition, when using UDP, it's not necessary for all the fragments to arrive at the destination so, preventing fragmentation means the message either arrives or doesn't arrive - there is no possibility that only a bit of the UDP datagram will reach the destination. I can't recall how long the TCP/IP stack held on to unassembled IP packets waiting for missing fragments, but use of the DF flag meant there were no unnecessary resources tied up during that time.
Finally, you can use it for testing behavior of network infrastructure, such as what happens when you get a packet that's bigger than the maximum transmission unit (DF will prevent that packet from being fragmented to 'squeeze through' the hole).
|
351,845
| 351,865
|
Finding the type of an object in C++
|
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.
What is the best way to find out which type the object passed to my function is?
|
dynamic_cast should do the trick
TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);
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.
If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception.
Make sure there is at least one virtual function in Base class to make dynamic_cast work.
Wikipedia topic Run-time type information
RTTI is available only for classes that are polymorphic, which means
they have at least one virtual method. In practice, this is not a
limitation because base classes must have a virtual destructor to
allow objects of derived classes to perform proper cleanup if they are
deleted from a base pointer.
|
351,864
| 352,920
|
Porting C++ lib/app on android
|
I want to port few C/C++ libraries to Android, how feasible it would be
e.g. OpenSSL can it be ported
or suppose an application which depends on OpenSSL, what is the best way to port it to Android when Android I think itself has libssl.so
what are the tools available e.g. Scratchbox, any alternatives?
Has anybody experience with it?
|
The android internals wiki is a good starting point, and includes a link explaining how to compile simple native applications.
Scratchbox does seem to be the way to go for compiling more complex apps & libraries, as you probably know already. I would suggest contacting those folks to get a bearing on your OpenSSL project.
|
352,152
| 352,235
|
Is there a dereference_iterator in the STL?
|
I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do:
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
vector<int*> vec;
int i = 1;
int j = 2;
int k = 3;
vec.push_back(&i);
vec.push_back(&j);
vec.push_back(&k);
copy(deref_iterator(vec.begin()),
deref_iterator(vec.end()),
ostream_iterator<int>(cout, " ")); // prints "1 2 3"
return 0;
}
|
Try Boost's indirect_iterator.
An indirect_iterator has the same category as the iterator it is wrapping. For example, an indirect_iterator<int**> is a random access iterator.
|
352,236
| 360,247
|
Reading from a text field in another application's window
|
Is there a way for a Windows application to access another applications data, more specifically a text input field in the GUI, and grab the text there for processing in our own application?
If it is possible, is there a way to "shield" your application to prevent it?
EDIT: The three first answers seem to be about getting the another applications window title, not a specific text input field in that window.
I'm no Windows API expert, so could you be more exact how do I find a certain text field in that window, what are the prerequisites for it (seems like knowing a window handle something is required, does it require knowing the text field handle as well? How do I get that? etc...)
Code snippets in C++ really would be really appreciated. MSDN help is hard to browse since Win32-API has such horrible naming conventions.
Completed! See my answer below for a how-to in C++.
|
For reading text content from another application's text box you will need to get that text box control's window handle somehow. Depending on how your application UI is designed (if it has a UI that is) there are a couple of different ways that you can use to get this handle. You might use "FindWindow"/"FindWindowEx" to locate your control or use "WindowFromPoint" if that makes sense. Either way, once you have the handle to the text control you can send a "WM_GETTEXT" message to it to retrieve its contents (assuming it is a standard text box control). Here's a concocted sample (sans error checks):
HWND hwnd = (HWND)0x00310E3A;
char szBuf[2048];
LONG lResult;
lResult = SendMessage( hwnd, WM_GETTEXT, sizeof( szBuf ) / sizeof( szBuf[0] ), (LPARAM)szBuf );
printf( "Copied %d characters. Contents: %s\n", lResult, szBuf );
I used "Spy++" to get the handle to a text box window that happened to be lying around.
As for protecting your own text boxes from being inspected like this, you could always sub-class your text box (see "SetWindowLong" with "GWL_WNDPROC" for the "nIndex" parameter) and do some special processing of the "WM_GETTEXT" message to ensure that only requests from the same process are serviced.
|
352,341
| 352,583
|
Multiple Integer-type classes in C++
|
I often find myself using Integers to represent values in different "spaces". For example...
int arrayIndex;
int usersAge;
int daysToChristmas;
Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a help from a documnentation perspective, but aren't type-safe enough.
I've tried wrapper classes, but end up with too much boilerplate for my liking. Is there a straightforward template-based solution, or maybe something ready-to-go in Boost?
EDIT: Several people have talked about bounds-checking in their answers. That maybe a handy side-effect, but is NOT a key requirement. In particular, I don't just want to prevent out-of-bound assignments, but assignments between "inappropriate" types.
|
You could try BOOST_STRONG_TYPEDEF. From boost/strong_typedef.hpp:
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
|
352,420
| 352,426
|
what is the difference between stringstream clear and str
|
I just wanted to know what's the difference between clear() and str("");
For example:
stringstream ss("Stack Overflow");
ss.clear();
ss.str("");
I wanted to know the underlying technical difference.
|
clear() clears the error state flags in the stringstream. That is to say it sets the error state to goodbit(which is equal to zero).
str("") sets the associated string object to the empty string.
They actually do completely different things. The peculiar choice of names only make it sound as though they perform similar tasks.
|
352,758
| 358,277
|
How to access to parent widget on qt?
|
I have an inherited QTreeWidget (called PackList) class and its parent is a KXmlGuiWindow.
How can I access to the parent's slots?
I've tried getParent()->mySlot() from the QTreeWidget class but I've got
error: no matching function for call to 'PackList::mySlot()'
Does anybody know the correct way? Thanks
|
If you know the parent's class, you will have to cast parentWidget() to that class and then call your slot. Keep in mind whether or not it's a slot makes no difference in this case. You are just calling a method.
((KXmlGuiWindow*)parentWidget())->mySlot();
You can make the call without casting by wiring up your signal to the slot.
connect( this, SIGNAL(mySignal()), parentWidget(), SLOT(mySlot()) );
Lastly, you can use QMetaObject::invokeMethod to call it if you don't want to cast it. That's probably overkill.
|
352,885
| 352,972
|
Dependency injection in C++
|
This is also a question that I asked in a comment in one of Miško Hevery's google talks that was dealing with dependency injection but it got buried in the comments.
I wonder how can the factory / builder step of wiring the dependencies together can work in C++.
I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A.
Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code:
class builder {
public:
builder() :
m_ClassA(NULL),m_ClassB(NULL) {
}
~builder() {
if (m_ClassB) {
delete m_ClassB;
}
if (m_ClassA) {
delete m_ClassA;
}
}
ClassA *build() {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB);
return m_ClassA;
}
};
Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like:
ClassA *builder::build(ClassC *classC) {
m_ClassB = new class B;
m_ClassA = new class A(m_ClassB, classC);
return m_ClassA;
}
What is your preferred approach?
|
This talk is about Java and dependency injection.
In C++ we try NOT to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object.
I find that most of the time dependency injection is done via references in C++.
In the rare cases where you must use pointers, wrap them in std::unique_ptr<> or std::shared_ptr<> depending on how you want to manage ownership.
In case you cannot use C++11 features, use std::auto_ptr<> or boost::shared_ptr<>.
I would also point out that C++ and Java styles of programming are now so divergent that applying the style of one language to the other will inevitably lead to disaster.
|
353,038
| 353,070
|
_endthreadex(0) hangs
|
I have some code which I did not originally create that uses _beginthreadex and _endthreadex. For some reason, when it calls _endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang?
|
_endthreadex ends the thread, so it can't return. That's the whole point of calling it.
EDIT: It's a bit unusual to call _endthreadex, normally you just let the thread start procedure return and the runtime calls _endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help.
|
353,180
| 353,217
|
How do I find the name of the calling function?
|
I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them.
In C++ how can I get the function name of the calling routine?
|
Here are two options:
You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the GNU backtrace functions. See my answer here for the details. This is probably the easiest thing.
If that isn't exactly what you're looking for, then you might try libunwind, but it's going to involve more work.
Keep in mind that this isn't something you can know statically (as with PRETTY_FUNCTION); you actually have to walk the stack to figure out what function called you. So this isn't something that's really worth doing in ordinary debug printfs. If you want to do more serious debugging or analysis, though, then this might be useful for you.
|
353,226
| 353,302
|
Facial recognition/merging software
|
Can anyone point me in the right direction of some facial recognition libraries & algorithms ? I've tried searching/googling but i mostly find thesises and very little real software.
|
How about Eigenfaces? Utilizes simple mathematics to store recognizable eigenvector of the face and reconstruct faces using multiple vectors.
The code is all available in Python as well here.
|
353,296
| 353,334
|
Best way to in situ delete an element
|
I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted.
My code goes as follows:
if( ! m_Container.empty() )
{
for( typedefedcontainer::iterator it = m_Container.begin();
it != m_Container.end();
++it )
{
if( ! ( SomeFunction( (*it), "test", "TEST!", false )) )
{
// If function returns false, delete object.
m_Container.erase( it );
AsyncResponseStore::iterator it = m_asyncResponses.begin();
}
}
}
But of course, when I erase an object I get an error : "Map / set iterator not incrementable". Can someone suggest a better way of doing this?
See:
What happens if you call erase() on a map element while iterating from begin to end?
|
It depends on the container. The list container supports deletion during enumeration by returning a new iterator from the erase method that represents the next item in the list. map doesn't support this.
A simple method for map is to accumulate the items you want to erase in a separate list, and then iterate over that list when you have finished processing the map to erase the items from the map. This assumes that you can defer the deletion until the iteration has completed. If not then you have no choice but the restart the iteration for each deletion.
|
353,464
| 15,201,457
|
Verbatim Literals in Managed C++? (like C#'s @"blah")
|
Is there a way to use verbatim String literals in managed C++? Similar to C#'s
String Docs = @"c:\documents and settings\"
|
in C++11, there is raw string literal:
cout<<R"((\"ddd\aa)\n)"<<endl;
cout<<R"delimiter((\"ddd\aa)\n)delimiter"<<endl;
output is:
(\"ddd\aa)\n
(\"ddd\aa)\n
|
353,550
| 353,640
|
Prevent creation of class whose member functions are all static
|
All the member variables and member functions in my class ClassA are static.
If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class.
Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?
Thank you
|
Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious:
class NonConstructible {
NonConstructible();
};
class SuperUtils: NonConstructible {
static void foo();
// ...
static std::vector<int> globalIDs;
// ...
};
Ok, now let's look into the namespace which are the one and only way to do this:
namespace SuperUtils {
void foo() {
// ....
}
std::vector<int> globalIDs;
};
You can call that using SuperUtils::foo(); in both cases, but the namespace has the advantage that in a scope you can use the namespace declaration and directive to bring certain or all members into the current scope, so that you can reference them without using SuperUtils:::
void superFunction() {
using namespace SuperUtils;
foo();
}
While generally that should be avoided, it can be helpful when the method is using exclusively much stuff from SuperUtils, which then can improve the readability of the code.
|
353,632
| 353,659
|
Why use = to initialise a primitive type in C++?
|
Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator:
std::string strFoo( "Foo" );
int nBar = 5;
Nobody seems to be able to explain why they prefer things this way, though. I can see that std::string = "Foo"; would be inefficient because it would involve an extra copy, but what's wrong with just banishing the = operator altogether and using parentheses everywhere?
Is it a common convention? What's the thinking behind it?
|
Unless you've proven that it matters with respect to performance, I wouldn't worry about an extra copy using the assignment operator in your example (std::string foo = "Foo";). I'd be pretty surprised if that copy even exists once you look at the optimized code, I believe that will actually call the appropriate parameterized constructor.
In answer to your question, yes, I'd say that it's a pretty common convention. Classically, people have used assignment to initialize built-in types, and there isn't a compelling reason to change the tradition. Readability and habit are perfectly valid reasons for this convention given how little impact it has on the ultimate code.
|
353,634
| 353,705
|
Are there any downsides to using UPX to compress a Windows executable?
|
I've used UPX before to reduce the size of my Windows executables, but I must admit that I am naive to any negative side effects this could have. What's the downside to all of this packing/unpacking?
Are there scenarios in which anyone would recommend NOT UPX-ing an executable (e.g. when writing a DLL, Windows Service, or when targeting Vista or Win7)? I write most of my code in Delphi, but I've used UPX to compress C/C++ executables as well.
On a side note, I'm not running UPX in some attempt to protect my exe from disassemblers, only to reduce the size of the executable and prevent cursory tampering.
|
... there are downsides to
using EXE compressors. Most notably:
Upon startup of a compressed EXE/DLL, all of the code is
decompressed from the disk image into
memory in one pass, which can cause
disk thrashing if the system is low on
memory and is forced to access the
swap file. In contrast, with
uncompressed EXE/DLLs, the OS
allocates memory for code pages on
demand (i.e. when they are executed).
Multiple instances of a compressed EXE/DLL create multiple
instances of the code in memory. If
you have a compressed EXE that
contains 1 MB of code (before
compression) and the user starts 5
instances of it, approximately 4 MB of
memory is wasted. Likewise, if you
have a DLL that is 1 MB and it is used
by 5 running applications,
approximately 4 MB of memory is
wasted. With uncompressed EXE/DLLs,
code is only stored in memory once and
is shared between instances.
http://www.jrsoftware.org/striprlc.php#execomp
|
353,694
| 353,725
|
How to cast QVariant to custom class?
|
I have a QVariant object within a QTreeWidgetItem, how can I cast it to my own object?
|
you need to declare somewhere in an .h file the following:
Q_DECLARE_METATYPE(MyStruct)
and then you can just use:
MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant
// retrieve the value
MyStruct s2 = var.value<MyStruct>();
see the docs here
|
353,817
| 353,890
|
Should every class have a virtual destructor?
|
Java and C# support the notion of classes that can't be used as base classes with the final and sealed keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?
Edit: Since C++11 this is no longer true, you can specify that a class is final.
On the one hand giving an object a virtual destructor means it will have a vtable and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the vptr.
On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous.
On the gripping hand having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically.
Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of this question) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do you think?
|
The question is really, do you want to enforce rules about how your classes should be used? Why?
If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough?
Or do you need the compiler to throw a hard error if anyone dares to do something you hadn't anticipated?
Give the class a virtual destructor if you intend for people to derive from it. Otherwise don't, and assume that anyone using your code is intelligent enough to use your code correctly.
|
354,329
| 354,343
|
Anyone know where a good windows constant list lives
|
I'm trying to set an invalid value to -1.. But I don't like magic numbers.. Anyone know where to find a set of common constants. I'm working in VS6 (ish).
I'm trying to read a file from across a network, and I need a bad value for the total file size,so I know if I got valid info on it.. 0 is a valid size so I can't use that.
Harper Shelby HIT THE NAIL ON THE HEAD.. Just a little thumb.
He mentioned the win32 constants.. which is exactly what I was thinking about.. Now to find a link :)
|
#define BAD_VALUE -1
EDIT: the original question had no context. The revised question indicates you want an invalid file size and are thus looking for the win32 constants. Look at windows.h i think the constant you seek may be in windows.h or one of its sub-includes. grep your windows include directory ;-)
|
354,442
| 354,481
|
Looking for C++ STL-like vector class but using stack storage
|
Before I write my own I will ask all y'all.
I'm looking for a C++ class that is almost exactly like a STL vector but stores data into an array on the stack. Some kind of STL allocator class would work also, but I am trying to avoid any kind of heap, even static allocated per-thread heaps (although one of those is my second choice). The stack is just more efficient.
It needs to be almost a drop in replacement for current code that uses a vector.
For what I was about to write myself I was thinking of something like this:
char buffer[4096];
stack_vector<match_item> matches(buffer, sizeof(buffer));
Or the class could have buffer space allocated internally. Then it would look like:
stack_vector<match_item, 256> matches;
I was thinking it would throw std::bad_alloc if it runs out of space, although that should not ever happen.
Update
Using Chromium's stack_container.h works great!
The reason I hadn't thought of doing it this way myself is that I have always overlooked the allocator object parameter to the STL collection constructors. I have used the template parameter a few times to do static pools but I'd never seen code or written any that actually used the object parameter. I learned something new. Very cool!
The code is a bit messy and for some reason GCC forced me to declare the allocator as an actual item instead of constructing it into vector's allocator parameter. It went from something like this:
typedef std::pair< const char *, const char * > comp_list_item;
typedef std::vector< comp_list_item > comp_list_type;
comp_list_type match_list;
match_list.reserve(32);
To this:
static const size_t comp_list_alloc_size = 128;
typedef std::pair< const char *, const char * > comp_list_item;
typedef StackAllocator< comp_list_item, comp_list_alloc_size > comp_list_alloc_type;
typedef std::vector< comp_list_item, comp_list_alloc_type > comp_list_type;
comp_list_alloc_type::Source match_list_buffer;
comp_list_alloc_type match_list_alloc( &match_list_buffer );
comp_list_type match_list( match_list_alloc );
match_list.reserve( comp_list_alloc_size );
And I have to repeat that whenever I declare a new one. But it works just like I wanted.
I noticed that stack_container.h has a StackVector defined and I tried using it. But it doesn't inherit from vector or define the same methods so it wasn't a drop-in replacement. I didn't want to rewrite all the code using the vector so I gave up on it.
|
You don't have to write a completely new container class. You can stick with your STL containers, but change the second parameter of for example std::vector to give it your custom allocator which allocates from a stack-buffer. The chromium authors wrote an allocator just for this:
https://chromium.googlesource.com/chromium/chromium/+/master/base/stack_container.h
It works by allocating a buffer where you say how big it is. You create the container and call container.reserve(buffer_size);. If you overflow that size, the allocator will automatically get elements from the heap (since it is derived from std::allocator, it will in that case just use the facilities of the standard allocator). I haven't tried it, but it looks like it's from google so i think it's worth a try.
Usage is like this:
StackVector<int, 128> s;
s->push_back(42); // overloaded operator->
s->push_back(43);
// to get the real std::vector.
StackVector<int, 128>::ContainerType & v = s.container();
std::cout << v[0] << " " << v[1] << std::endl;
|
354,607
| 504,085
|
How to get the document CDHtmlDialog after Asp.Net AJAX UpdatePanel
|
When the page displayed in our CDHtmlDialog does an Asp.Net AJAX UpdatePanel we get a navigate event, but everything after that seems to be lost. We don't have a document anymore or get any mouse events on the page.
|
Looks like I made the original post as an unregistered user, so I don't think I can edit it. We were able to work around the original issue, but it came up again in a different context (really starting to hate CDHTMLDialog).
Here is the cause of the problem:
Javascript calls are causing a Navigate event, and CDHtmlDialog::OnBeforeNavigate gets called and disconnects and deletes the IHTMLDocument2. Unfortunately it's not a true Navigate since the page never changed. This means CDHtmlDialog::OnNavigateComplete is never called to get the document back.
To make matters worse, when I override CDHtmlDialog::OnBeforeNavigate I find the URL string is unreadable (bug)?
The simplest (best?) solution:
We need to intercept the Before Navigate event, and only call the CDHtmlDialog's _OnBeforeNavigate2 if the URL isn't a javascript action:
BEGIN_EVENTSINK_MAP(CMyHTMLDlg, CDHtmlDialog)
ON_EVENT(CMyHTMLDlg, AFX_IDC_BROWSER, DISPID_BEFORENAVIGATE2, OnBeforeNavigate2, VTS_DISPATCH VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_VARIANT VTS_PBOOL)
END_EVENTSINK_MAP()
void CMyHTMLDlg::OnBeforeNavigate2(LPDISPATCH pDisp, VARIANT* URL,VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData,VARIANT* Headers, BOOL* Cancel)
{
...
if (URL != NULL)
{
// Check if navigation is to a folder..
CString url = CString(*URL);
if(url.Left(11) != _T("javascript:"))
{
_OnBeforeNavigate2(pDisp, URL, Flags, TargetFrameName, PostData, Headers, (BOOL*)Cancel);
// If dynamic linking MFC then the above handler doesn't exist. Need to call OnBeforeNavigate direct.
// This is from a code site, and it compiles, but I've never tested it to see if it works.
//CDHtmlDialog::OnBeforeNavigate(pDisp,(LPCSTR)URL);
}
}
}
Most of this is pretty standard for setting up a CDHtmlDialog subclass, and it's pretty simple actually, but it took me a bit to figure out how to handle JavaScript. Unfortunately, I'm not sure how this will work if the JavaScript is making dynamic changes to the page itself.
A couple notes:
If the navigation needs to be completely canceled here, then set *Cancel = TRUE and don't call _OnBeforeNavigate2. Be careful here because this also cancels any JavaScript actions.
It wasn't clear until I saw the source, but CDHtmlDialog::_OnBeforeNavigate2 just calls CDHtmlDialog::OnBeforeNavigate.
|
354,613
| 354,621
|
convert bitmap to byte array
|
How can I convert a bitmap to a byte array in c++ WITHOUT the .net framework?
|
If you’re using Windows, you can use GetDIBits to retrieve the bitmap data.
|
355,258
| 355,302
|
Why must const members be initialized in the constructor initializer rather than in its body?
|
Why must class members declared as const be initialized in the constructor initializer list rather than in the constructor body?
What is the difference between the two?
|
In C++, an object is considered fully initialised when execution enters the body of the constructor.
You said:
"i wanted to know why const must be
intialized in constructor initializer
list rather than in it's body ?."
What you are missing is that initialisation happens in the initialisation list, and assignment happens in the body of the constructor. The steps in logic:
1) A const object can only be initialised.
2) An object has all of its members initialised in the initialisation list. Even if you do not explicitly initialise them there, the compiler will happily do so for you :-)
3) Therefore, putting 1) and 2) together, a member which is const can only ever have a value assigned to it at initialisation, which happens during the initialisation list.
|
355,650
| 412,985
|
C++ HTML template framework, templatizing library, HTML generator library
|
I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.
It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.
Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters.
Do you have any recommendations?
I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.
|
A quick review of the mentioned project.
http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language
ClearSilver
Site: http://www.clearsilver.net
Project: https://code.google.com/p/clearsilver/
Group: http://tech.groups.yahoo.com/group/ClearSilver
License: New BSD License
Language: C
Last Update: Nov 28, 2011
Last Release: 0.10.5 on July 12, 2007
Document: Rich
Community: Medium (<10 discussion per month)
Teng
Site: http://teng.sourceforge.net
Code: http://teng.svn.sourceforge.net/teng/
Group: http://sourceforge.net/projects/teng/
License: New BSD License
Language: C++
Binding: php, python
Last Update: Mar 8, 2011
Last Release: 2.1.1 on Mar 8, 2011
Document: Rich
Community: Low (rare discussion since 2010)
Templatizer
Site: http://www.lazarusid.com/libtemplate.shtml
Project: download only
Group: none
License: free to use
Language: C (low level)/C++ (interface) mixed
Last Update: unknown
Last Release: unknown
Document: none
Community: none
HTML Template C++
Site: http://nulidex.com/code/docs/html_template/
Project: http://sourceforge.net/projects/htmltemplatec
Group: http://sourceforge.net/projects/htmltemplatec
License: GPL
Language: C++
Last Update: Mar 27, 2011
Last Release: Beta 0.7.4, Mar 27, 2011
Document: Medium
Community: none
ctpp
Site: http://ctpp.havoc.ru/en/
Project: download only
Group: none
License: BSD License
Language: C++ with C API
Last Update: Oct 5, 2011
Last Release: Version 2.7.2 on Oct 5, 2011
Document: Rich
Community: none
Wt
Site: http://www.webtoolkit.eu/wt/
Project: http://www.webtoolkit.eu/wt/
Group: http://www.webtoolkit.eu/wt/community
License: GPL and Commercial
Language: C++
Last Update: Nov 29, 2011
Last Release: 3.2.0 on Nov 29, 2011
Document: Rich
Community: Low (rare activity)
Flate
Site: http://flate.dead-inside.org/
Project: none
Group: none
License: LGPL v2.1
Language: C
Last Update: Sep 4, 2010
Last Release: 2.0 on Sep 4, 2010
Document: Poor
Community: none
Jinja2C++
Site: https://jinja2cpp.dev
Project: https://github.com/jinja2cpp
Group: https://gitter.im/Jinja2Cpp/Lobby
Conan packages: https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview
License: MPL-2.0
Language: C++14/17
Last Update: Oct 01, 2019
Last Release: 1.0.0 on Oct 01, 2019
Document: Moderate
Community: none
|
355,690
| 1,771,896
|
Symbian C++ STOMP library
|
I want my S60 Application to utilize the Stomp protocol.
Although it would be fairly simple to implement myself (but nothing is ever as simple as I hope with Symbian) - I am wondering if anyone has any experience in this already.
It seems a Stomp library exists in almost every other language already. The closest match for Symbian would be the C++ library listed here but that is embedded quite integrally within the ActiveMQ source.
Can anyone offer any advice/experience?
Thanks!
|
In case this is still relevant - I've just finished my implementation of a STOMP client for Symbian, fully using the Active Scheduler framework. We're going to release it as opensource once I get something set up on Google Code.
As Adam says - the implementation needed to be purely within the Symbian framework or it would be unusable (i.e. you'd either need to thread it - arg - or it would just cause all sorts of blocking problems).
I'd also like to get in touch with the STOMP people and have it listed on the website, but haven't been able to find a contact - does anyone here know the best way to do it?
|
355,958
| 416,820
|
How to detect deadlock whith Asio library?
|
i have little problem with boost::asio library. My app receive and process data asynchronously, it create threads and run io_service.run() on each of them.
boost::asio::io_service io;
boost::thread_group thread_pool;
...
int cpu_cnt = get_cpu_count();
for (int i = 0; i < cpu_cnt; ++i)
{
thread_pool.create_thread( boost::bind(&run_service, &io) );
}
void run_service(boost::asio::io_service* io)
{
try
{
io->run();//make fun
}
catch(const std::exception& e)
{ //process error
}
catch(...)
{ //process error
}
}
Time after time, my application receives message(across windows messaging system) from some supervisor application that checks is my program alive or not. If my application wont reply, it will be restarted. The tricky part here is to check, that threads is running and not deadlocked. I can post handler to io_service like this:
io.post( &reply_to_supervisor );
but this method affects only one thread.
How can i check that all threads is running and not deadlocked?
|
I may be wrong, but would the use an io_service per thread solve your problem?
Another idea: post cpu_cnt times reply_to_supervisor calls that use a little sleep() - not nice, but should work
|
356,002
| 357,043
|
How to erase elements from boost::ptr_vector
|
So I'm trying to get rid of my std::vector's by using boost::ptr_vector. Now I'm trying to remove an element from one, and have the removed element deleted as well. The most obvious thing to me was to do:
class A
{ int m; };
boost::ptr_vector<A> vec;
A* a = new A;
vec.push_back(a);
vec.erase(a);
But this won't even compile (see below for the full error message). I've tried the erase/remove idiom like I would on a std::vector but all the algorithms of boost::ptr_vector turn out to be slightly different from those in std::vector.
So my questions:
How do I remove a pointer from a ptr_vector?
Do I still need to manually delete() that element that I removed?
Compiler error:
1>------ Build started: Project: ptr_vector_test, Configuration: Debug Win32 ------
1>Compiling...
1>ptr_vector_test.cpp
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2825: 'C': must be a class or namespace when followed by '::'
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\mpl\eval_if.hpp(63) : see reference to class template instantiation 'boost::range_const_iterator<C>' being compiled
1> with
1> [
1> C=A *
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\range\iterator.hpp(63) : see reference to class template instantiation 'boost::mpl::eval_if_c<C,F1,F2>' being compiled
1> with
1> [
1> C=true,
1> F1=boost::range_const_iterator<A *>,
1> F2=boost::range_mutable_iterator<A *const >
1> ]
1> c:\users\rvanhout\svn\trunk\thirdparty\boost\ptr_container\detail\reversible_ptr_container.hpp(506) : see reference to class template instantiation 'boost::range_iterator<C>' being compiled
1> with
1> [
1> C=A *const
1> ]
1> c:\tmp\ptr_vector_test\ptr_vector_test.cpp(21) : see reference to function template instantiation 'boost::void_ptr_iterator<VoidIter,T> boost::ptr_container_detail::reversible_ptr_container<Config,CloneAllocator>::erase<A*>(const Range &)' being compiled
1> with
1> [
1> VoidIter=std::_Vector_iterator<void *,std::allocator<void *>>,
1> T=A,
1> Config=boost::ptr_container_detail::sequence_config<A,std::vector<void *,std::allocator<void *>>>,
1> CloneAllocator=boost::heap_clone_allocator,
1> Range=A *
1> ]
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2039: 'const_iterator' : is not a member of '`global namespace''
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2146: syntax error : missing ';' before identifier 'type'
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : error C2208: 'boost::type' : no members defined using this type
1>c:\users\rvanhout\svn\trunk\thirdparty\boost\range\const_iterator.hpp(37) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://c:\tmp\ptr_vector_test\Debug\BuildLog.htm"
1>ptr_vector_test - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
|
Well you can do that with a std::vector either.
In both cases erase takes an iterator as a parameter.
So before you can erase something from a vector (or a ptr_vector) you need to locate it.
Also note that the ptr_vector treats its content as if you have stored an object not a pointer. So any searching is done via the object.
So basically
std::vector<A> x;
std::ptr_vector<A> y;
// These two object should behave in exactly the same way.
// The ONLY difference is inserting values which for y are pointers.
// Y take ownership of the pointer and all subsequent acesses to the
// members of y look like they are objects
Example:
#include <boost/ptr_container/ptr_vector.hpp>
#include <vector>
class A
{ int m;
public:
A(int x):m(x) {}
bool operator==(A const& rhs) {return m = rhs.m;}
};
int main()
{
boost::ptr_vector<A> x;
x.push_back(new A(1));
x.erase(std::find(x.begin(),x.end(),A(1)));
std::vector<A> y;
y.push_back(A(2));
y.erase(std::find(y.begin(),y.end(),A(2)));
// To find an exact pointer don't modify the equality.
// Use find_if and pass a predicate that tests for a pointer
A* a = new A(3);
boost:ptr_Vector<A> z;
z.push_back(a);
z.erase(std::find_if(y.begin(),y.end(),CheckPointerValue(a));
}
struct CheckPointerValue
{
CheckPointerValue(A* a):anA(a) {}
bool operator()(A const& x) { return &X == anA;}
private:
A* anA;
};
|
356,726
| 356,728
|
Is 'bool' a basic datatype in C++?
|
I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this:
int i = true;
Is it "always" guaranteed that variable i will have value 1 or is it again depends on the compiler I am using ? Further for some Win32 APIs which accept BOOL as the parameter what happens if I pass bool variable?
|
bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like
enum bool {
false, true
};
So did the Windows API. Starting with C99, we have _Bool as a basic data type. Including stdbool.h will typedef #define that to bool and provide the constants true and false. They didn't make bool a basic data-type (and thus a keyword) because of compatibility issues with existing code.
|
356,950
| 356,993
|
What are C++ functors and their uses?
|
I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?
|
A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function:
// this is a functor
struct add_x {
add_x(int val) : x(val) {} // Constructor
int operator()(int y) const { return x + y; }
private:
int x;
};
// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument
std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out(in.size());
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i
There are a couple of nice things about functors. One is that unlike regular functions, they can contain state. The above example creates a function which adds 42 to whatever you give it. But that value 42 is not hardcoded, it was specified as a constructor argument when we created our functor instance. I could create another adder, which added 27, just by calling the constructor with a different value. This makes them nicely customizable.
As the last lines show, you often pass functors as arguments to other functions such as std::transform or the other standard library algorithms. You could do the same with a regular function pointer except, as I said above, functors can be "customized" because they contain state, making them more flexible (If I wanted to use a function pointer, I'd have to write a function which added exactly 1 to its argument. The functor is general, and adds whatever you initialized it with), and they are also potentially more efficient. In the above example, the compiler knows exactly which function std::transform should call. It should call add_x::operator(). That means it can inline that function call. And that makes it just as efficient as if I had manually called the function on each value of the vector.
If I had passed a function pointer instead, the compiler couldn't immediately see which function it points to, so unless it performs some fairly complex global optimizations, it'd have to dereference the pointer at runtime, and then make the call.
|
357,243
| 357,327
|
I think STL is causing my application triple its memory usage
|
I am inputting a 200mb file in my application and due to a very strange reason the memory usage of my application is more than 600mb. I have tried vector and deque, as well as std::string and char * with no avail. I need the memory usage of my application to be almost the same as the file I am reading, any suggestions would be extremely helpful.
Is there a bug that causes so much memory consumption? Could you pinpoint the problem or should I rewrite the whole thing?
Windows Vista SP1 x64, Microsoft Visual Studio 2008 SP1, 32Bit Release Version, Intel CPU
The whole application until now:
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <time.h>
static unsigned int getFileSize (const char *filename)
{
std::ifstream fs;
fs.open (filename, std::ios::binary);
fs.seekg(0, std::ios::beg);
const std::ios::pos_type start_pos = fs.tellg();
fs.seekg(0, std::ios::end);
const std::ios::pos_type end_pos = fs.tellg();
const unsigned int ret_filesize (static_cast<unsigned int>(end_pos - start_pos));
fs.close();
return ret_filesize;
}
void str2Vec (std::string &str, std::vector<std::string> &vec)
{
int newlineLastIndex(0);
for (int loopVar01 = str.size(); loopVar01 > 0; loopVar01--)
{
if (str[loopVar01]=='\n')
{
newlineLastIndex = loopVar01;
break;
}
}
int remainder(str.size()-newlineLastIndex);
std::vector<int> indexVec;
indexVec.push_back(0);
for (unsigned int lpVar02 = 0; lpVar02 < (str.size()-remainder); lpVar02++)
{
if (str[lpVar02] == '\n')
{
indexVec.push_back(lpVar02);
}
}
int memSize(0);
for (int lpVar03 = 0; lpVar03 < (indexVec.size()-1); lpVar03++)
{
memSize = indexVec[(lpVar03+1)] - indexVec[lpVar03];
std::string tempStr (memSize,'0');
memcpy(&tempStr[0],&str[indexVec[lpVar03]],memSize);
vec.push_back(tempStr);
}
}
void readFile(const std::string &fileName, std::vector<std::string> &vec)
{
static unsigned int fileSize = getFileSize(fileName.c_str());
static std::ifstream fileStream;
fileStream.open (fileName.c_str(),std::ios::binary);
fileStream.clear();
fileStream.seekg (0, std::ios::beg);
const int chunks(1000);
int singleChunk(fileSize/chunks);
int remainder = fileSize - (singleChunk * chunks);
std::string fileStr (singleChunk, '0');
int fileIndex(0);
for (int lpVar01 = 0; lpVar01 < chunks; lpVar01++)
{
fileStream.read(&fileStr[0], singleChunk);
str2Vec(fileStr, vec);
}
std::string remainderStr(remainder, '0');
fileStream.read(&remainderStr[0], remainder);
str2Vec(fileStr, vec);
}
int main (int argc, char *argv[])
{
std::vector<std::string> vec;
std::string inFile(argv[1]);
readFile(inFile, vec);
}
|
Your memory is being fragmented.
Try something like this :
HANDLE heaps[1025];
DWORD nheaps = GetProcessHeaps((sizeof(heaps) / sizeof(HANDLE)) - 1, heaps);
for (DWORD i = 0; i < nheaps; ++i)
{
ULONG HeapFragValue = 2;
HeapSetInformation(heaps[i],
HeapCompatibilityInformation,
&HeapFragValue,
sizeof(HeapFragValue));
}
|
357,307
| 357,380
|
How to call a parent class function from derived class function?
|
How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within
each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?
|
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
|
357,404
| 357,464
|
Why are unnamed namespaces used and what are their benefits?
|
I just joined a new C++ software project and I'm trying to understand the design. The project makes frequent use of unnamed namespaces. For example, something like this may occur in a class definition file:
// newusertype.cc
namespace {
const int SIZE_OF_ARRAY_X;
const int SIZE_OF_ARRAY_Y;
bool getState(userType*,otherUserType*);
}
newusertype::newusertype(...) {...
What are the design considerations that might cause one to use an unnamed namespace? What are the advantages and disadvantages?
|
Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:
namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }
The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.
This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.
namespace { int a1; }
static int a2;
Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.
Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).
|
357,481
| 357,551
|
writing 2d arrays to output files - c++
|
I'm trying to write a 2d array into an output file, it's all working fine except in creating the .getline function to draw the array back out of the file. My issue is putting the string length. My current code for the line is;
inputFile.getline(myArray, [10][10], '\n');
but it doesn't like having the string length in square brackets it seems, what should I do?
thanks in advance
|
For that to compile, myArray must be an array of char, or a char*. In particular, it is a one-dimensional array. To read multiple dimensions, you'll need to read each row separately. The second parameter to std::istream::getline is the maximum number of chars to read and store in the array, minus one.
To begin reading something from a file, you should start by knowing how the file was written to in the first place. You know how the file was created, I hope, but you haven't described that in your question. Knowing how the file was written is essential for knowing how to read from it. Show some code, please.
|
357,564
| 358,823
|
Uses for anonymous namespaces in header files
|
Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization.
Am I remembering correctly? Can someone fill in the details?
|
The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers.
The token ignore for tuples, mentioned in another answer is one example, the _1, _2 etc. bind placeholders are others.
|
357,629
| 357,638
|
How do you find the range of values that integer types can represent in C++?
|
The size and range of the integer value types in C++ are platform specific. Values found on most 32-bit systems can be found at Variables. Data Types. - C++ Documentation. How do you determine what the actual size and range are for your specific system?
|
C Style
limits.h contains the min and max values for ints as well as other data types which should be exactly what you need:
#include <limits.h> // C header
#include <climits> // C++ header
// Constant containing the minimum value of a signed integer (–2,147,483,648)
INT_MIN;
// Constant containing the maximum value of a signed integer (+2,147,483,647)
INT_MAX;
For a complete list of constants and their common values check out: Wikipedia - limits.h
C++ Style
There is a template based C++ method as other commenters have mentioned using:
#include <limits>
std::numeric_limits
which looks like:
std::numeric_limits<int>::max();
and it can even do craftier things like determine the number of digits possible or whether the data type is signed or not:
// Number of digits for decimal (base 10)
std::numeric_limits<char>::digits10;
// Number of digits for binary
std::numeric_limits<char>::digits;
std::numeric_limits<unsigned int>::is_signed;
|
357,898
| 381,321
|
How to reload a 3rd party DLL that crashes often
|
I'm using a 3rd party DLL written in unmanaged C++ that controls some hardware we have.
Unfortunately this DLL crashes now and then and I've been tasked to make it "reload" automagically. I'm not too sure about how to proceed to get best results.
My project uses C++.Net 2.0 (2005). I'm wrapping the 3rd party stuff in a separate DLL. I've been trying to FreeLibrary() and LoadLibrary(). However when I FreeLibrary(), some internal DLL dependencies remain allocated and LoadLibrary() will make it crash because of corrupted memory.
Another approach that was suggested was to refactor the whole project using .NET remoting interfaces. It would make it easier to kill another process and restart it but it will be a lot of work.
Any suggestions? Pointers? Hints?
|
The most effective approach will be to not load that DLL in your application's process at all. Instead, create a second process whose only job is to use that DLL on behalf of your application. You can use a shared memory region, local socket, or other IPC mechanism to control the proxy process.
This way, when the problematic DLL crashes, you can simply allow the proxy process to die without worrying about the (nearly impossible) task of trying to make sure the DLL didn't corrupt anything important on its way down. Your main process need only start a new instance of the proxy process and carry on.
|
357,963
| 358,115
|
std::ifstream::open() not working
|
I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently:
std::ifstream stream;
stream.open("rules.ini");
if (!stream.is_open())
{
throw new std::exception("Rule file could not be opened");
}
// read file contents here
stream.close();
However, my stream never opens succesfully. Diving deep into the STL source during debugging reveals that _getstream() (as defined in stream.c) keeps on returning NULL, but I just can't figure out why this is. Help, anyone?
Edit: Rules.ini is in the same directory as the .exe file.
|
You are assuming that the working directory is the directory that your executable resides in. That is a bad assumption.
Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software.
If you want to be able to access files relative to the location of your executable, you should first determine the path of your executable and create a fully qualified path from that.
You can get the name of your executable by examining the argv[0] parameter passed to main(). Alternatively, if you're on Windows, you can get it with GetModuleFileName() by passing NULL as the first parameter.
|
358,533
| 358,581
|
How important is Boost to learn for C++ developers?
|
I am curious to learn Boost. But I wanted to ask:
How important is it to make the effort to learn Boost?
What prerequisites should one have before jumping on Boost?
Why I am curious to know about Boost is that many people are talking about Boost on IRC's channels and here in StackOverflow.
|
I think anyone that is seriously considering C++ development as a career should learn Boost, and learn it well. Once you get into serious programming you will realize how beneficial these libraries can be and how much more productive they can make you. Not only are they cross-platform, but once you get into data crunching with large numbers, the math libraries especially will seem like a gift from above.
|
358,972
| 359,279
|
Unwanted xmlns="" in _di_IXMLNode
|
I'm creating a xml-file for display in Excel using _di_IXMLDocument. But for some tags I get an unwanted extra (empty) xmlns attribute witch makes the file unreadable for Excel...
This is what i do:
...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("ss:Name",Now().DateString());
...
and this is what comes out:
<Worksheet xmlns="" ss:Name="2008-12-11">
Where does xmlns come from? How do I get rid of it?
EDIT:
Some more info: If I try to add a xmlns attribute to Worksheet myself, like this:
...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("xlmns","Foo");
worksheet->SetAttribute("ss:Name",Now().DateString());
...
Then the child nodes of "Worksheet" all get the empty xmlns attributes instead!
<Worksheet xmlns="Foo" ss:Name="2008-12-11">
<Table xmlns="">
|
Ok I had a look at this question. The trick was to create the child nodes and telling the what namespace they belong to, and then not to output it...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet","workbooks-namespace",false);
worksheet->SetAttribute("ss:Name",Now().DateString());
this produces the desired output:
<Worksheet ss:Name="2008-12-11">
|
359,084
| 359,558
|
How to capture high resolution image on Windows Mobile
|
I would like to capture high resolution image with Windows Mobile device. I've tried the example from WM SDK, but it captures just a single frame of video camera and the resolution is poor.
Has anyone any experience with image capturing on Pocket PC with C++?
Thanks
|
You need to change the filter used by the example code to capture a high-resolution image. When you use the viewfinder in a digital camera, the camera "simulates" a video camera look by applying the lowest resolution filter and then rapidly taking and displaying single frames. When you click the button to take a high-res picture, the camera has to swap out the low-res filter for the high-res filter and then take the high-res picture - this is why (cheap) digital cameras always take so long to snap a picture.
I don't know which code example you're working with, but if it's the one I used it defaults to using the lowest resolution filter. There should be a line in it somewhere that selects the filter. You just need to change the value passed from 0 to (probably) 3 or 4 for the highest resolution.
|
359,732
| 359,753
|
Why is it considered a bad practice to omit curly braces?
|
Why does everyone tell me writing code like this is a bad practice?
if (foo)
Bar();
//or
for(int i = 0 i < count; i++)
Bar(i);
My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
for (int x = 0; x <= GlowAmount; x++)
{
for (int y = 0; y <= GlowAmount; y++)
{
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
}
}
}
//versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
for (int x = 0; x <= GlowAmount; x++)
for (int y = 0; y <= GlowAmount; y++)
g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
You can also get the added benefit of chaining usings together without having to indent a million times.
using (Graphics g = Graphics.FromImage(bmp))
{
using (Brush brush = new SolidBrush(backgroundColor))
{
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
}
}
//versus
using (Graphics g = Graphics.FromImage(bmp))
using (Brush brush = new SolidBrush(backgroundColor))
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
//do lots of work
}
The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:
if (foo)
Bar();
Biz();
Questions:
Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.
Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it?
Is there another argument that I'm missing?
|
Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():
if(foo)
// bar();
doSomethingElse();
Other than that, I tend to use:
if(foo) bar();
Which takes care of the above case.
EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.
|
359,885
| 362,100
|
Symbian C++ - S60 application launches through TRK and Carbide, but not afterwards or when downloaded
|
My application has just started exhibiting strange behaviour.
I can boot it through the Carbide Debugger (using TRK) and it works fine with no visible errors and is left installed on the device.
Any further attempts to launch the application fail, even after a restart. Uninstalling and downloading the .sisx file manually also doesn't work.
Has anyone had any experience like this? Could it be some resource file that is missing, or is there any other way I can find out what is happening?
|
You should install ErrRd sis file to enable your phone to show extended panics - maybe this will give you some hints. If you get "Menu -1" then most probably you are missing some resource file or library. Also if you use DLL files then check that they have at least the same capabilities than your EXE file.
|
359,928
| 365,738
|
Which C++ signals/slots library should I choose?
|
I want to use a signals/slots library in a project that doesn't use QT. I have pretty basic requirements:
Connect two functions with any number of parameters.
Signals can be connected to multiple slots.
Manual disconnection of signal/slot connection.
Decent performance - the application is frame-based (i.e. not event-based) and I want to use the connections in each frame.
I've read a comparison between libsigc++ and Boost.Signals. I've also read that Boost.Signals suffers from poor performance. However, I know there are other libraries and I'm still not sure which library should I choose.
Are there any recommendations for a signals/slots library?
|
First, try with boost::signal anyway. Don't assume it will not be fast enough until you try in your specific case that is your application
If it's not efficient enough, maybe something like FastDelegate will suit your needs? (i did'nt try it but heard it was a nice solution in some cases where boost::signal don't seem to suit).
Anyway, if in your application use the signal each frame, it may be worth to replace the signal system by something more simple, like a container that hold objects/functors that will be called each frame. Signal is more made to allow immediate "events" management than to make a loop cycle dynamic (allowing changing the functions called each frame).
(I have my own solution (UPDATE: it's very old and archaic now) that i heavily use in a game and for instance i've no problem with the performance, so maybe something similar could help).
|
359,992
| 360,032
|
S60 application - Symbian C++ - Exit button doesn't work
|
In my Symbian S60 application, my Options menu works as expected. But the Exit button does nothing.
I am developing with Carbide and have used the UI Designer to add items to the options menu.
Does anyone know how to enable the exit button, or why else it might not work?
Thanks!
|
Are you handling (in your appui::HandleCommandL) command ids EEikCmdExit and EAknSoftkeyExit?
if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit )
{
Exit();
}
|
360,154
| 360,190
|
Native C++ SQL Framework
|
I need a high performance framework in native C++ for SQL.
I need it to be able to use MySQL, Oracle and Microsoft SQL Server and provide abstraction
from the lower level problems/idiosyncrasies found in every different syntax required for by DBMS from different vendors. Something like LINQ for C# and VB .Net.
|
I believe that Qt has at least some of what you're looking for
|
360,338
| 360,372
|
C#/Java programmer learning C++ again. Project file structure?
|
As the question states, i am a C#/Java programmer who is interested in (re)learning C++. As you know C#/Java have a somewhat strict project file structure (especially Java). I find this structure to be very helpful and was wondering if it is a) good practice to do a similar structure in a C++, b) if so, what is the best way to setup it up?
i know there is the basic 'headers' and 'source' folders, but is there a better way?
|
I find the structure of java projects quite nice. I do it like this (root is the root directory)
root/include/foo/bar/baz.hpp becomes
namespace foo {
namespace bar {
// declare/define the stuff (classes, functions) here
} } // foo::bar
in code.
I keep the source in
root/src/foo/bar/baz.cpp . If i have some stuff that is not exposed to the outside, i put it into a detail/ directory and namespace. I keep the makefiles at root/.
|
361,312
| 361,407
|
C++ developing a GUI - classes?
|
I do have to say I'm fairly inexperienced when it comes to C++, don't be too harsh on me.
Recently stumbled unto the wonders of the win32 API and have chosen to practice using it (I'd rather not use MFC/wxWidgets/etc at this point, just for educational purposes).
Well, my real question is:
How do you properly code your win32 GUI stuff into classes. I mean, sure, you can make a class that saves individual window handles, allows for easier modification of window properties, has a more simplified version of CreateWindow(). But as I understand it you will need a messagepump and several callback functions for your created windows. How does that work when combining them with classes?
Could anyone point me in the right direction here? I don't mind reading (a lot of) example code as long as it is commented.
PS: I'm also having trouble finding good (read: easy) documentation on using 'resource files' for my window decorations. Bonuspoints for that! :)
|
The biggest problem I faced back when I used the Win32 API (have since moved on to Linux and cross-platform solutions) were the callbacks. Especially the winproc one, AKA the message pump. I found this, which should be a good hint. I did what that page suggests when I rolled my own wrapper.
|
361,500
| 361,597
|
initializing std::string from char* without copy
|
I have a situation where I need to process large (many GB's) amounts of data as such:
build a large string by appending many smaller (C char*) strings
trim the string
convert the string into a C++ const std::string for processing (read only)
repeat
The data in each iteration are independent.
My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.
Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?
Alternatively, could I use stringstreams or something similar to re-use a large buffer?
Edit: Thanks for the answers, for clarity, I think a revised question would be:
How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.
|
Is it at all possible to use a C++ string in step 1? If you use string::reserve(size_t), you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps.
See this link for more information on the reserve function.
|
361,648
| 361,674
|
How do you make linux GUI's?
|
My main experience is with C && C++, so I'd prefer to remain with them. I don't want to use anything like QT, GTK, or wxWidgets or any tool kits. I'd like to learn native programming and this sort of defeats the purpose. With that in mind I'd also like to avoid Java.
I understand gnome and xfce and KDE and such are all Desktop Environments for Linux, and the base installed typically is X (Xorg). When coding for Linux, do you code for X, or for the desktop environment? Is there a standard Linux header for this (like win32 has windows.h) for Linux? or is it different coding methods for every desktop environment?
any help is greatly appreciated.
|
X is a hideous layer to program for and, despite your intent to avoid Java, QT or any of the excellent UI abstraction layers, you'll be doing yourself a disservice by coding to that level. I've done it (a long time ago when Motif was in its infancy on the platform we were using) and I would not do it again if there was an easier way.
Your use of the phrase "native programming" confuses me a little. If you want to learn native programming, it's to the APIs that you choose to call. Using similar reasoning, you shouldn't be coding in C either, instead opting for assembler (or direct machine code) since C provides an abstraction to the hardware.
If you want to learn X programming, that's fine. You'll end up with a lot more control over your interface but almost everyone else will be out-performing you in terms of delivery of software. Myself, I'd prefer to code to a higher-level API that I can use on many platforms - it gives me both faster delivery times and more market potential.
You don't build a house out of atoms, you build it out of bricks. My suggestion is to use the tools, that's what they're there for.
|
361,730
| 361,780
|
VS2008 binary 3x times slower than VS2005?
|
I've just upgraded a native C++ project from VS2005-SP1 to VS2008-SP1
The first thing I tested was a very basic functionality test of the application and the first thing I noticed is that the main number-crunching algorithm performs three times slower in the VS2008 binary.
I tested again the VS2005 binary to make sure there isn't any other difference and it still performed as it did before.
Did anyone stumble into this?
|
Strangest. Thing. Ever.
It seems that the project upgrade wizard of vs2008 simply doesn't copy the 'Optimization="2"' property so the new project is left with no optimization in release.
The fix was to go to the properties dialog, change optimization to 1 and then back to 2.
compile again and everything works it should.
I couldn't find any official reference for this only this obscure reference in an MSDN forum.
|
362,225
| 362,340
|
Setting Zoom on Windows Mobile device with IAMCameraControl::Set()
|
I am developing an application for video capture and I would like to implement zoom functionality.
Working with DirectShow I came across IAMCameraControlInterface. It has a method ::Set(), which should be used for setting several camera parameters.
However I played around and I couldn't do anything with it. Then I tried to call ::GetRange() method which should return the range of possible parameter values but it didn't return anything.
Is it really possible that the device doesn't support any option? It seems very strange because the native camera application supports zoom, but I really don't know where could be the main problem for such strange results.
Has anyone any experience with similar applications? Does anyone know what could be wrong here or how to effectively use IAMCameraControlInterface functions?
|
I don't have any personal experience, but have a look at this forum port. According to a replier, the driver may not implement the IAMCameraControl interface correctly and rely on implementation specific tricks to do zoom in and out.
As far as I know (please someone correct or verify it) the camera driver isn't part of the Windows Mobile certification process. This means that the manufacturer can do as he pleases with it.
|
362,260
| 362,268
|
Thread safety and `const`
|
How does const (pointers, references and member functions) help with thread safety in C++?
|
The main problem with multiple threads is mutability. const restricts this, but since you can cast away the const-ness, it's not foolproof.
|
362,570
| 368,093
|
Carbide / Symbian C++ - Change Application Icon
|
I am using Carbide (just upgraded to 2.0) to develop an S60 3rd Edition application.
I would like to know the easiest way to change the icon (both the application icon on the device menu and the icon at the top left of the main view) because I have the need to skin my application in many different ways as easily as possible.
All my efforts with messing around with .mif files have so far failed. I have a 44x44 .svg icon I made with Illustrator, could someone please help me in the right direction?
Thanks!
|
To change the app icon when you run your app use (in the status bar):
CEikStatusPane* sp=iEikonEnv->AppUiFactory()->StatusPane();
CAknContextPane* cp=(CAknContextPane *)sp->ControlL(TUid::Uid(EEikStatusPaneUidContext));
_LIT(KContextBitMapFile, "my_bitmap_file.mbm");
CFbsBitmap* bitmap = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmap);
CleanupStack::PushL(bitmap);
CFbsBitmap* bitmapmask = iEikonEnv->CreateBitmapL(KContextBitMapFile, EMbmBitmapMask);
CleanupStack::PushL(bitmapmask);
cp->SetPicture(bitmap, bitmapmask);
CleanupStack::Pop(); // bitmapmask
CleanupStack::Pop(); // bitmap
DrawNow();
I'm not aware of any possibility of changing the app icon in the menu list programmatically, other than reinstalling the app with different mif file.
|
362,822
| 362,892
|
How do I export templated classes from a dll without explicit specification?
|
I have a dll that contains a templated class. Is there a way to export it without explicit specification?
|
Since the code for templates is usually in headers, you don't need to export the functions at all. That is, the library that is using the dll can instantiate the template.
This is the only way to give users the freedom to use any type with the template, but in a sense it's working against the way dlls are supposed to work.
|
362,928
| 362,943
|
Open source C++ library for vector mathematics
|
I would need some basic vector mathematics constructs in an application. Dot product, cross product. Finding the intersection of lines, that kind of stuff.
I can do this by myself (in fact, have already) but isn't there a "standard" to use so bugs and possible optimizations would not be on me?
Boost does not have it. Their mathematics part is about statistical functions, as far as I was able to see.
Addendum:
Boost 1.37 indeed seems to have this. They also gracefully introduce a number of other solutions at the field, and why they still went and did their own. I like that.
|
Re-check that ol'good friend of C++ programmers called Boost. It has a linear algebra package that may well suits your needs.
|
363,007
| 363,033
|
How to reposition/resize the resource on the screen?
|
I want to embed the native camera application into custom form.
The RECT r properties where I want to embed the camera are the following:
r.top = 26;
r.bottom = 220;
r.left = 0;
r.right = 320;
and this is the method which runs the native camera application:
HRESULT CPhotoCapture::CameraCapture(HWND hwndOwner, LPTSTR pszFilename)
{
HRESULT hResult;
SHCAMERACAPTURE shcc;
//Set the SHCAMERACAPTURE structure
ZeroMemory(&shcc, sizeof(shcc));
shcc.cbSize = sizeof(shcc);
shcc.hwndOwner = hwndOwner;
shcc.pszInitialDir = _T("\\My Documents");
shcc.pszDefaultFileName = _T("test.jpg");
shcc.pszTitle = _T("Camera Demo");
shcc.StillQuality = CAMERACAPTURE_STILLQUALITY_HIGH;
shcc.VideoTypes = CAMERACAPTURE_VIDEOTYPE_MESSAGING;
shcc.nResolutionWidth = 1024;
shcc.nResolutionHeight = 768;
shcc.nVideoTimeLimit = 15;
shcc.Mode = CAMERACAPTURE_MODE_STILL;
//display the camera capture dialog
hResult = SHCameraCapture(&shcc);
if(hResult == S_OK)
{
//TODO:: Write to log
}
return hResult;
}
The method above is called from the window which dimensions are equal to r:
HRESULT hr = S_OK;
hr = m_PhotoCapture.CameraCapture(this->m_hWnd, L"test");
Does anyone know how to modify the above function (hwndOwner) the way to display the embedded resource in the rectangle r?
|
You're not too clear on what hwndOwner points to. My **guess* on how this probably works is that you need to create a Window that is a child of your main display Window whose location matches your rect (and is visible), then pass it's handle in and that the capture API then uses DShow to pipe the output of the frame grabs from the camera to that Window that the handle represents.
|
363,160
| 364,815
|
How do I set the ideal QPixmapCache::cacheLimit?
|
I have just started using QPixmapCache and I was wondering, since there is not much documentation, about how to adjust the size based on the system the application is running on.
Some users might have lots of free memory while others have very little. I have no idea what the best setting would be.
What would be the best way to detect the system (free) RAM and adjust the cache size to fit?
http://doc.trolltech.com/4.4/qpixmapcache.html#setCacheLimit
|
To detect free RAM in Windows, you can use the GlobalMemoryStatus function.
I'm not sure if this will help you size the pixmap cache; perhaps you will need to do some performance measurements and create a lookup table.
|
363,292
| 363,338
|
Why is Visual C++ lacking refactor functionality?
|
When programming in C++ in Visual Studio 2008, why is there no functionality like that seen in the refactor menu when using C#?
I use Rename constantly and you really miss it when it's not there. I'm sure you can get plugins that offer this, but why isn't it integrated in to the IDE when using C++? Is this due to some gotcha in the way that C++ must be parsed?
|
The syntax and semantics of C++ make it incredibly difficult to correctly implement refactoring functionality. It's possible to implement something relatively simple to cover 90% of the cases, but in the remaining 10% of cases that simple solution will horribly break your code by changing things you never wanted to change.
Read http://yosefk.com/c++fqa/defective.html#defect-8 for a brief discussion of the difficulties that any refactoring code in C++ has to deal with.
Microsoft has evidently decided to punt on this particular feature for C++, leaving it up to third-party developers to do what they can.
|
363,302
| 363,378
|
openGL textures that are not 2^x in dimention
|
I'm trying to display a picture in an openGL environment. The picture's origninal dimensions are 3648x2432, and I want to display it with a 256x384 image. The problem is, 384 is not a power of 2, and when I try to display it, it looks stretched. How can I fix that?
|
There's three ways of doing this that I know of -
The one Albert suggested (resize it until it fits).
Subdivide the texture into 2**n-sized rectangles, and piece them together in some way.
See if you can use GL_ARB_texture_non_power_of_two. It's probably best to avoid it though, since it looks like it's an Xorg-specific extension.
|
363,336
| 368,431
|
Trouble tracking down a potential memory overwrite. Windows weirdness
|
This is driving me nuts. I am using some 3rd-party code in a Windows .lib that, in debug mode, is causing an error similar to the following:
Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted.
The error is thrown when either the object goes out of scope or is deleted. Simply allocating one of these objects and then deleting it will throw the error. I therefore think the problem is either in one of the many constructors/destructors but despite stepping through every line of code I cannot find the problem.
However, this only happens when creating one of these objects in a static library. If I create one in my EXE application, the error does not appear. The 3rd-party code itself lives in a static lib. For example, this fails:
**3RDPARTY.LIB**
class Foo : public Base
{
...
};
**MY.LIB**
void Test()
{
Foo* foo = new Foo;
delete foo; // CRASH!
}
**MY.EXE**
void Func()
{
Test();
}
But this will work:
**3RDPARTY.LIB**
class Foo : public Base
{
...
};
**MY.EXE**
void Func()
{
Foo* foo = new Foo;
delete foo; // NO ERROR
}
So, cutting out the 'middle' .lib file makes the problem go away and it is this weridness that is driving me mad. The EXE and 2 libs all use the same CRT library. There are no errors linking. The 3rd-party code uses inheritance and there are 5 base classes. I've commented out as much code as I can whilst still getting it to build and I just can't see what's up.
So if anyone knows why code in a .lib would act differently to the same code in a .exe, I would love to hear it. Ditto any tips for tracking down memory overwrites! I am using Visual Studio 2008.
|
OK, I tracked the problem down and it's a cracker, if anyone's interested. Basically, my .LIB, which exhibited the problem. had defined _WIN32_WINNT as 0x0501 (Windows 2000 and greater), but my EXE and the 3rd-party LIB had it defined as 0x0600 (Vista). Now, one of the headers included by the 3rd-party lib is sspi.h which defines a structure called SecurityFunctionTable which includes the following snippet:
#if OSVER(NTDDI_VERSION) > NTDDI_WIN2K
// Fields below this are available in OSes after w2k
SET_CONTEXT_ATTRIBUTES_FN_W SetContextAttributesW;
#endif // greater thean 2K
Th cut a long story short, this meant a mismatch in object sizes between the LIBs and this was causing the Run-Time Check Failure.
Class!
|
363,351
| 376,362
|
Once you've adopted boost's smart pointers, is there any case where you use raw pointers?
|
I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?
|
Just a few off the top of my head:
Navigating around in memory-mapped files.
Windows API calls where you have to over-allocate (like a LPBITMAPINFOHEADER).
Any code where you're munging around in arbitrary memory (VirtualQuery() and the like).
Just about any time you're using reinterpret_cast<> on a pointer.
Any time you use placement-new.
The common thread here is "any situation in which you need to treat a piece of memory as something other than a resource over which you have allocation control".
|
363,453
| 403,171
|
Looking for a better C++ class factory
|
I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components.
What I've done is derive all of the objects from a base BrokeredObject class:
class BrokeredObject
{
virtual int GetInterfaceId() = 0;
};
And each object type returns a unique ID. These IDs are maintained in a header file.
I then have an ObjectBroker "factory". When someone needs an object, then call GetObjectByID(). The boker looks in an STL list to see if the object already exists, if it does, it returns it. If not, it creates it, puts it in the list and returns it. All well and good.
BrokeredObject *GetObjectByID(int id)
{
BrokeredObject *pObject;
ObjectMap::iterator = m_objectList.find(id);
// etc.
if(found) return pObject;
// not found, so create
switch(id)
{
case 0: pObject = new TypeA; break;
case 1: pObject = new TypeB; break;
// etc.
// I loathe this list
}
// add it to the list
return pObject;
}
What I find painful is maintaining this list of IDs and having to have each class implement it. I have at least made my consumer's lives slightly easier by having each type hold info about it's own ID like this:
class TypeA : public BrokeredObject
{
static int get_InterfaceID() { return IID_TYPEA; }
int GetInterfaceID() { return get_InterfaceID(); }
};
So I can get an object like this:
GetObjectByID(TypeA::get_InterfaceID());
Intead of having to actually know what the ID mapping is but I still am not thrilled with the maintenance and the potential for errors. It seems that if I know the type, why should I also have to know the ID?
What I long for is something like this in C#:
BrokeredObject GetOrCreateObject<T>() where T : BrokeredObject
{
return new T();
}
Where the ObjectBroker would create the object based on the type passed in.
Has C# spoiled me and it's just a fact of life that C++ can't do this or is there a way to achieve this that I'm not seeing?
|
My use-case tended to get a little more complex - I needed the ability to do a little bit of object initialization and I needed to be able to load objects from different DLLs based on configuration (e.g. simulated versus actual for hardware). It started looking like COM and ATL was where I was headed, but I didn't want to add the weight of COM to the OS (this is being done in CE).
What I ended up going with was template-based (thanks litb for putting me on track) and looks like this:
class INewTransModule
{
public:
virtual bool Init() { return true; }
virtual bool Shutdown() { return true; }
};
template <typename T>
struct BrokeredObject
{
public:
inline static T* GetInstance()
{
static T t;
return &t;
}
};
template <>
struct BrokeredObject<INewTransModule>
{
public:
inline static INewTransModule* GetInstance()
{
static INewTransModule t;
// do stuff after creation
ASSERT(t.Init());
return &t;
}
};
class OBJECTBROKER_API ObjectBroker
{
public:
// these calls do configuration-based creations
static ITraceTool *GetTraceTool();
static IEeprom *GetEeprom();
// etc
};
Then to ensure that the objects (since they're templated) actually get compiled I added definitions like these:
class EepromImpl: public BrokeredObject<EepromImpl>, public CEeprom
{
};
class SimEepromImpl: public BrokeredObject<SimEepromImpl>, public CSimEeprom
{
};
|
363,760
| 2,218,783
|
Windows Explorer directory as bundle
|
I have been investigating for some time now a way to prevent my user from accidently entering a data directory of my application.
My application uses a folder to store a structured project. The folder internal structure is critic and should not be messed up. I would like my user to see this folder as a whole and not be able to open it (like a Mac bundle).
Is there a way to do that on Windows?
Edit from current answers
Of course I am not trying to prevent my users from accessing their data, just protecting them from accidentally destroying the data integrity. So encryption or password protection are not needed.
Thank you all for your .Net answers but unfortunately, this is mainly a C++ project without any dependency to the .Net framework.
The data I am mentioning are not light, they are acquired images from an electronic microscope. These data can be huge (~100 MiB to ~1 GiB) so loading everything in memory is not an option. These are huge images so the storage must provide a way to read the data incrementally by accessing one file at a time without loading the whole archive in memory.
Besides, the application is mainly legacy with some components we are not even responsible of. A solution that allows me to keep the current IO code is preferable.
Shell Extension looks interesting, I will investigate the solution further.
LarryF, can you elaborate on Filter Driver or DefineDOSDevice ? I am not familiar with these concepts.
|
Looks like some Windows ports of FUSE are starting to appear. I think this would be the best solution since it would allow me to keep the legacy code (which is quite large) untouched.
|
363,864
| 363,873
|
invalid types 'int[int]' for array subscript
|
This code throws up the compile error given in the title, can anyone tell me what to change?
#include <iostream>
using namespace std;
int main(){
int myArray[10][10][10];
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
myArray[i][t][x][y] = i+t+x+y; //This will give each element a value
}
}
}
}
for (int i = 0; i <= 9; ++i){
for (int t = 0; t <=9; ++t){
for (int x = 0; x <= 9; ++x){
for (int y = 0; y <= 9; ++y){
cout << myArray[i][t][x][y] << endl;
}
}
}
}
system("pause");
}
thanks in advance
|
You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.
|
364,017
| 364,156
|
Faster bulk inserts in sqlite3?
|
I have a file of about 30000 lines of data that I want to load into a sqlite3 database. Is there a faster way than generating insert statements for each line of data?
The data is space-delimited and maps directly to an sqlite3 table. Is there any sort of bulk insert method for adding volume data to a database?
Has anyone devised some deviously wonderful way of doing this if it's not built in?
I should preface this by asking, is there a C++ way to do it from the API?
|
You can also try tweaking a few parameters to get extra speed out of it. Specifically you probably want PRAGMA synchronous = OFF;.
|
364,146
| 364,163
|
C++ syntax help dealing with recursive definition (or so my compiler tells me)
|
I'm building a game and I was compiling seeing what sort of errors were coming up and there is one there is very common and very puzzling to me:
1>c:\users\owner\desktop\bosconian\code\bosconian\ship.h(9) : error C2460: 'Ship::Coordinate' : uses 'Ship', which is being defined
This also comes up for the SpaceObject class and all other derivations of it. The Coordinate class is simply just a 2d vector class and, if it matters, references nothing but an Environment class.
The Environment class references the SpaceObject's but I don't believe that's a problem (correct me if I'm wrong)
This is my first larger scale project in C++ and I was wondering if this might be a common newbie error with a more obvious solution. If it matters the SpaceObject class hierarchy is not all the way filled in, but it is filled in several levels past the SpaceObject and Ship classes.
.
.
.
Edit: This is in response to the comment.
-When I say reference I mean refer to that class in another class. Like in the SpaceObject class I reference the Coordinate class:
Coordinate * position
Environment does make reference to SpaceObject pointers, but I can't see I could not reference classes like that...I mean, all my classes have to relate to eachother in some way, right?
In response to pasting code, it's sort of hard because they are huge classes but here is the line the error is pointing to:
public:
Ship(Coordinate * positionObject_, int direction_, int possibleDirections_, int maxHealth_, Component * objectSectors_, int numOfObjectSectors_, double speed_);//this is the line
void move();//handles the actual translation of calculated move on the map (i.e. bounds checking)
|
You've got something like this:
class Ship
{
class Coordinate
{
Ship m_ship;
};
Coordinate m_coordinate;
};
The problem is that each Ship object contains as a member a Coordinate, which contains as a member a Ship, ad nauseum. The size of a Ship would become infinitely large if this were allowed to continue. What you really want is to replace those member variables with pointers or references - a pointer/reference has a known size (e.g. 4 bytes on a 32-bit CPU), and can be declared without knowing any information about the type being pointed/referred to.
|
364,209
| 364,224
|
variable or field declared void
|
I have a function called:
void initializeJSP(string Experiment)
And in my MyJSP.h file I have:
2: void initializeJSP(string Experiment);
And when I compile I get this error:
MyJSP.h:2 error: variable or field initializeJSP declared void
Where is the problem?
|
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.
|
364,240
| 364,257
|
How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)?
|
How do YOU reduce compile time, and linking time for VC++ projects (native C++)?
Please specify if each suggestion applies to debug, release, or both.
|
It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in:
// Forward declaration stuff
namespace plotter { namespace logic { class Plotter; } }
// Real stuff
namespace plotter {
namespace samples {
class Window {
logic::Plotter * mPlotter;
// ...
};
}
}
It greatly reduces the time for compiling also on others compilers. Indeed it applies to all configurations :)
|
364,985
| 365,068
|
Algorithm for finding the smallest power of two that's greater or equal to a given value
|
I need to find the smallest power of two that's greater or equal to a given value. So far, I have this:
int value = 3221; // 3221 is just an example, could be any number
int result = 1;
while (result < value) result <<= 1;
It works fine, but feels kind of naive. Is there a better algorithm for that problem?
EDIT. There were some nice Assembler suggestions, so I'm adding those tags to the question.
|
Here's my favorite. Other than the initial check for whether it's invalid (<0, which you could skip if you knew you'd only have >=0 numbers passed in), it has no loops or conditionals, and thus will outperform most other methods. This is similar to erickson's answer, but I think that my decrementing x at the beginning and adding 1 at the end is a little less awkward than his answer (and also avoids the conditional at the end).
/// Round up to next higher power of 2 (return x if it's already a power
/// of 2).
inline int
pow2roundup (int x)
{
if (x < 0)
return 0;
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x+1;
}
|
365,048
| 365,055
|
Interesting C++ Abstract Function
|
why this is happen ?
When u create abstract class in c++ Ex: Class A (which has a pure virtual function)
after that class B is inherited from class A
And if class A has constructor called A()
suppose i created an Object of class B then the compiler initializes the base class first i.e.class A and then initialize the class B Then.......?
First thing is we can not access a constructor of any class without an Object then how it is initialize the constructor of abstract class if we can not create an object of abstract class .
|
Quick answer: constructors are special.
When the constructor of A is still running, then the object being constructed is not yet truly of type A. It's still being constructed. When the constructor finishes, it's now an A.
It's the same for the derived B. The constructor for A runs first. Now it's an A. Then the constructor for B starts running. During this, the object is still really an A. Only when B's constructor finishes does it become a B.
You can verify this by trying to call the pure virtual function from the constructors. If the function is defined in A, and B's constructor calls it, there will be a runtime error instead of running B's override, because the object is not of type B yet.
The compiler will not allow you to generate code that will construct an A, due to the pure virtual function. But it will generate code to construct an A as part of the process of constructing a B. There's no magic involved in this. The rule that you cannot construct an A is imposed by the language rules, not by physics. The language lifts that rule under the special circumstance of constructing objects of B.
|
365,104
| 365,111
|
Why are destructors required in C++?
|
When a pointer goes out of scope, its memory is freed, so why are destructors created in c++?
|
If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example.
Also, 'unscoping' a pointer does not free the memory that it points to since other pointers may be referencing it.
If you have a pointer on the stack, exiting the function will free the memory used by the pointer but not that memory pointed to by the pointer. There's a subtle but very important distinction.
|
365,198
| 365,206
|
Getting this BST template to work
|
hI, I'm trying to get this code from Larry Nyhoff's book to compile in Bloodshed. It's actually been taken word for word from the author's website, though I declared it on .cpp instead of .h (the .h file ain't working with the tester application).
http://cs.calvin.edu/activities/books/c++/ds/2e/SourcePrograms/Chap12/
The search(const DataType & item) function is what's giving me grief. The compiler error says:
In member function `bool BST<DataType>::search(const DataType&) const':
expected `;' before "locptr"
`locptr' undeclared (first use this function)
What I'm I missing here?
#include <iostream>
#ifndef BINARY_SEARCH_TREE
#define BINARY_SEARCH_TREE
template <typename DataType>
class BST
{
public:
/***** Function Members *****/
BST();
bool empty() const;
bool search(const DataType & item) const;
void insert(const DataType & item);
void remove(const DataType & item);
void inorder(std::ostream & out) const;
void graph(std::ostream & out) const;
private:
/***** Node class *****/
class BinNode
{
public:
DataType data;
BinNode * left;
BinNode * right;
// BinNode constructors
// Default -- data part is default DataType value; both links are null.
BinNode()
: left(0), right(0)
{}
// Explicit Value -- data part contains item; both links are null.
BinNode(DataType item)
: data(item), left(0), right(0)
{}
}; //end inner class
typedef BinNode * BinNodePointer;
/***** Private Function Members *****/
void search2(const DataType & item, bool & found,
BinNodePointer & locptr, BinNodePointer & parent) const;
/*------------------------------------------------------------------------
Locate a node containing item and its parent.
Precondition: None.
Postcondition: locptr points to node containing item or is null if
not found, and parent points to its parent.#include <iostream>
------------------------------------------------------------------------*/
void inorderAux(std::ostream & out,
BST<DataType>::BinNodePointer subtreePtr) const;
/*------------------------------------------------------------------------
Inorder traversal auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Subtree with root pointed to by subtreePtr has been
output to out.
------------------------------------------------------------------------*/
void graphAux(std::ostream & out, int indent,
BST<DataType>::BinNodePointer subtreeRoot) const;
/*------------------------------------------------------------------------
Graph auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Graphical representation of subtree with root pointed
to by subtreePtr has been output to out, indented indent spaces.
------------------------------------------------------------------------*/
/***** Data Members *****/
BinNodePointer myRoot;
}; // end of class template declaration
//--- Definition of constructor
template <typename DataType>
inline BST<DataType>::BST()
: myRoot(0)
{}
//--- Definition of empty()
template <typename DataType>
inline bool BST<DataType>::empty() const
{ return myRoot == 0; }
//--- Definition of search()
template <typename DataType>
bool BST<DataType>::search(const DataType & item) const
{
BST<DataType>::BinNodePointer locptr = myRoot; //**THIS FAILS, WHY?**//
bool found = false;
while (!found && locptr != 0)
{
if (item < locptr->data) // descend left
locptr = locptr->left;
else if (locptr->data < item) // descend right
locptr = locptr->right;
else // item found
found = true;
}
return found;
}
#endif
|
Put a typename before the declaration:
typename BST<DataType>::BinNodePointer locptr = myRoot;
The point is that due to potential template specialization, the compiler cannot know that the dependent identifier BinNodePointer identifies a type.
|
365,316
| 365,466
|
3D Engine Comparison
|
I am currently investigating several free/open source OpenGL based 3D engines, and was wondering if you guys could provide some feedback on these engines and how they are to work with in a real world project.
The engines being compared are (in no particular order):
Crystal Space
Panda3D
Irrlicht
These are the main ones i know that are cross-platform, any there any others that i should be looking at?
|
You can find a lot of informations on lot of engines on this database.
CrystalSpace is a full engine so it's a monolithic bloc that you have to customize for your needs.
Irrlicht too but it's made do do things easy. The counter effect is that it's hard to do specific things.
Now, i think Ogre might be the most general purpose hardware accelerated 3D rendering engine around here. Maybe Horde3D is better suited for specific high quality rendering but nothing that cannot be done with Ogre too.
|
365,458
| 365,796
|
How can I detect if a program is running from within valgrind?
|
Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects std::vector::reserve to throw std::bad_alloc. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) and behavior (expecting the exception to be thrown).
Here's a minimal example that reproduces it:
#include <vector>
int main()
{
size_t uint_max = static_cast<size_t>(-1);
std::vector<char> v;
v.reserve(uint_max);
}
Running valgrind, I get this output:
Warning: silly arg (-1) to __builtin_new()
new/new[] failed and should throw an exception, but Valgrind
cannot throw exceptions and so is aborting instead. Sorry.
at 0x40192BC: VALGRIND_PRINTF_BACKTRACE (valgrind.h:319)
by 0x401C823: operator new(unsigned) (vg_replace_malloc.c:164)
by 0x80487BF: std::vector<char, std::allocator<char> >::reserve(unsigned) new_allocator.h:92)
by 0x804874D: main (vg.cxx:6)
I'd like to modify my unit test to simply skip the offending code when it's being run from within valgrind. Is this possible?
|
You should look at this page from the Valgrind manual, it contains a RUNNING_ON_VALGRIND macro (included from valgrind.h) which does what you want.
|
365,476
| 365,492
|
C++ Problem Stuffing 8 bits into a char
|
This is weird. It is a trivial problem:
A std::string with bits with length multiple of 8, the first 8 is: "10011100".
//Convert each 8 bits of encoded string to bytes
unsigned char c = 0;
for(size_t i = 0; i < encoded.size(); i += 8)
{
for(size_t k = 0; k < 8; k++)
{
c <<= k;
if(encoded.at(i + k) == '1') c += 1;
//Debug for first 8 bits
if(i == 0) cout << "at k = " << k << ", c = " << (int)c << endl;
}
outFile.write(reinterpret_cast<char*>(&c), sizeof(char));
}
Yields the output:
at k = 0, c = 1
at k = 1, c = 2
at k = 2, c = 8
at k = 3, c = 65
at k = 4, c = 17
at k = 5, c = 33
at k = 6, c = 64
at k = 7, c = 0
Which doesn't make sense. Shifting 2 places left and getting 8 from 2 is impossible. The max value it can have should be 111b = 7d and in this case should be 100b = 4d.
Enlight me.
|
at k = 0, c = 1
at k = 1, c = 2
at k = 2, c = 8
That is because:
input = 10011100
c = 0
`k=0, b=1` shift by 0 add 1 => `c = 1`, dec = 1
`k=1, b=0` shift by 1 add 0 => `c = 10`, dec = 2
`k=2, b=0` shift by 2 add 0 => `c = 1000`, dec = 8
b means "current bit". Possibly you don't want to shift by k, but by 1 ? If you look for a standard C++ solution, you can use std::bitset:
std::bitset<8> bits("10011100");
unsigned char c = bits.to_ulong();
For your output into the stream, you can use the put function:
outFile.put(c);
It avoids casting pointers and also outputs unformatted (settings like the field-width are ignored).
|
365,650
| 365,668
|
Visual Studio skips build
|
When I try to build my project I get the following message in the build window :
========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========
I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info on what's wrong . I am using Visual Studio 2005 Professional Edition .
|
Check with the configuration manager like CMS said and make sure that you have the right platform set. A lot of the time when you use something like the MS Application Blocks the default platform is set to Itanium.
|
365,823
| 365,862
|
What kinds of interview questions are appropriate for a c++ phone screen?
|
Curious to get people's thoughts. I conduct frequent interviews, and have had enough in my career to reflect on them, and I've noticed a broad array of questions. I made this c++ specific, but it's worth noting that I have had people ask me algorithmic complexity questions over the phone, and I don't even mean what is the complexity of a hash lookup vs. a binary tree, I mean more like analytical problems, such as "imagine there are 4 bumble bees, each buzzing bla bla bla."
Now personally I prefer to keep phone screens a little more concrete, and leave the abstract questions for the white board. So when conducting c++ phone interviews, what kind of topics do you cover, especially for Sr. developers?
I know there is another thread similar to this, but frankly it seems to completely have missed the point that this is about phone screens, not interviews that are face to face. Plus this is more c++ specific.
|
I'd ask about resource/memory management, because it's an important subject in C++, and it doesn't require concrete code. Just sketch a simple hypothetical scenario, and ask how they'd ensure some vital resource gets freed even in the face of errors/exceptions. Say they're developing a network app, how do they ensure that we close our sockets properly? Of course the proper answer would be to wrap it in a RAII object, but don't ask them that directly (it's easy to google "RAII", while the above question "how would you ensure resources get released properly" actually shows you whether or not they know the appropriate techniques. If they answer "wrap everything in try/catch", they might have a problem. And this ties in nicely with questions about the differences between heap and stack.
You might be able to come up with some simple question about exception safety too, which doesn't require any real code. In general, I'd say a discussion of all the various C++ idioms might be a good idea, because many of them don't require much actual code, but are still vital language-specific concepts.
See if they know about smart pointers (again preferably by giving them a situation where smart pointers are called for, and see how they would solve the problem), and maybe templates/metaprogrammin (in the latter case, probably just find out if they're aware that it's possible ,rather than requiring them to code actual metaprograms on the phone)
You might also want to ask about some common areas of undefined behavior (what are the values of a and b after executing a = b++ + b++??), or allocate an array of 10 elements, and add 10 or 11 to the array pointer, and ask what the result is in each case (+=10 is legal, gives you a past-the-end pointer, +=11 is undefined). Or give them a scenario where they need to copy a lot of objects, and ask how they'd do that (plain for-loop copying each element at a time, memcpy or std::copy are obvious answers. Note the caveats with memcpy, that it's not safe for non-POD objects)
Or ask about their coding style in general. How do they feel about iterators? Do they prefer plain old for-loops? Do they know how to use std::for_each or std::transform?
Edit:
Seems the a = b++ + b++ (the answer is undefined behavior, btw) suggestion in particular generated a lot of comments. Perhaps people read too much into it. As the OP said he preferred to ask concrete (not abstract, and easy to explain/answer/discuss over the phone) questions, that'd reveal a bit about the interviewee's C++ skills, and this is a simple (and yes, perhaps nitpicky) example of that. The reasoning behind it is that 1) it has an intuitive meaning, which is wrong, and 2) you have to have a certain level of experience with C++ before you realize this. And of course 3), it's short and easy to ask over the phone. It doesn't require anyone to write code down. No, it won't reveal whether the candidate is a "great programmer", but as I understood the question, that wasn't the goal either. If someone gets it wrong, it doesn't mean much at all, but if they get it right, you can be fairly sure that they know a bit of C++. But if you read my answer again, you'll see that it was just a quick example of a category of questions I thought should be represented. C++ is full of undefined behavior, even in code that looks completely harmless and intuitive. Asking the candidate to recognize some instance of this may be useful, whether it's the "modify the same variable twice in the same expression" example above, or something different.
|
365,887
| 365,891
|
How do 'malloc' and 'new' work? How are they different (implementation wise)?
|
I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation?
See What is the difference between new/delete and malloc/free?
|
I'm just going to direct you to this answer: What is the difference between new/delete and malloc/free? . Martin provided an excellent overview. Quick overview on how they work (without diving into how you could overload them as member functions):
new-expression and allocation
The code contains a new-expression supplying the type-id.
The compiler will look into whether the type overloads the operator new with an allocation function.
If it finds an overload of an operator new allocation function, that one is called using the arguments given to new and sizeof(TypeId) as its first argument:
Sample:
new (a, b, c) TypeId;
// the function called by the compiler has to have the following signature:
operator new(std::size_t size, TypeOfA a, TypeOfB b, TypeOf C c);
if operator new fails to allocate storage, it can call new_handler, and hope it makes place. If there still is not enough place, new has to throw std::bad_alloc or derived from it. An allocator that has throw() (no-throw guarantee), it shall return a null-pointer in that case.
The C++ runtime environment will create an object of the type given by the type-id in the memory returned by the allocation function.
There are a few special allocation functions given special names:
no-throw new. That takes a nothrow_t as second argument. A new-expression of the form like the following will call an allocation function taking only std::size_t and nothrow_t:
Example:
new (std::nothrow) TypeId;
placement new. That takes a void* pointer as first argument, and instead of returning a newly allocated memory address, it returns that argument. It is used to create an object at a given address. Standard containers use that to preallocate space, but only create objects when needed, later.
Code:
// the following function is defined implicitly in the standard library
void * operator(std::size_t size, void * ptr) throw() {
return ptr;
}
If the allocation function returns storage, and the the constructor of the object created by the runtime throws, then the operator delete is called automatically. In case a form of new was used that takes additional parameters, like
new (a, b, c) TypeId;
Then the operator delete that takes those parameters is called. That operator delete version is only called if the deletion is done because the constructor of the object did throw. If you call delete yourself, then the compiler will use the normal operator delete function taking only a void* pointer:
int * a = new int;
=> void * operator new(std::size_t size) throw(std::bad_alloc);
delete a;
=> void operator delete(void * ptr) throw();
TypeWhosCtorThrows * a = new ("argument") TypeWhosCtorThrows;
=> void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc);
=> void operator delete(void * ptr, char const* arg1) throw();
TypeWhosCtorDoesntThrow * a = new ("argument") TypeWhosCtorDoesntThrow;
=> void * operator new(std::size_t size, char const* arg1) throw(std::bad_alloc);
delete a;
=> void operator delete(void * ptr) throw();
new-expression and arrays
If you do
new (possible_arguments) TypeId[N];
The compiler is using the operator new[] functions instead of plain operator new. The operator can be passed a first argument not exactly sizeof(TypeId)*N: The compiler could add some space to store the number of objects created (necassary to be able to call destructors). The Standard puts it this way:
new T[5] results in a call of operator new[](sizeof(T)*5+x), and
new(2,f) T[5] results in a call of operator new[](sizeof(T)*5+y,2,f).
|
366,028
| 14,005,292
|
What is a good C/C++ CSS parser?
|
What is a good C/C++ CSS parser? All that I can find is CSSTidy, and it seems to be more of an application than a parsing library.
|
libcss seems also a common google hit and it looks good
http://www.netsurf-browser.org/projects/libcss/
|
366,134
| 366,138
|
Can you declare a pointer as extern in C++?
|
I have the following bit of legacy C++ code that does not compile:
#include <stdio.h>
#include <iostream>
extern ostream *debug;
GCC (g++) complains: "expected initializer before ‘*’ token"
Looking around it seems more common to declare these as external references, like this:
extern ostream& debug;
Why is a pointer not valid, but a reference is in this situation?
SOLUTION:
The real problem, as mentioned below is that the std:: namespace specifier is missing. Apparently, this was common in older C++ code.
|
Yes, you can declare a pointer using extern. Your error is most likely you forgot to qualify using std:: :
// note the header is cstdio in C++. stdio.h is deprecated
#include <cstdio>
#include <iostream>
extern std::ostream *debug;
|
366,228
| 366,268
|
.def files C/C++ DLLs
|
I am not understanding the point of using .def files with DLLs.
It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit __declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL.
So how do you use .defs when linking with the client application, do they replace the need to use a header or .lib file?
|
My understanding is that .def files provide an alternative to the __declspec(dllexport) syntax, with the additional benefit of being able to explicitly specify the ordinals of the exported functions. This can be useful if you export some functions only by ordinal, which doesn't reveal as much information about the function itself (eg: many of the OS internal DLL's export functions only by ordinal).
See the reference page.
Note that the names in the .def file must match the names in the binary. So if you using C or C++ with 'extern "C" { ... }', the names will not be mangled; otherwise you must use the correct mangled names for the specific version of the compiler used to generate the DLL. The __declspec() function does this all automatically.
|
366,257
| 366,266
|
Everything a c++ developer should know about network programming?
|
So I am doing a lot of high performance network programming using Boost::Asio (or just Asio if you will), and have a pretty solid grasp of the essentials of both TCP and UDP protocols. I am wondering though, because I still don't consider myself an expert in networking despite my knowledge, what is a good way to frame the essentials of what networking programmers should know, especially for those trying to push the performance of their large networking based applications?
There is a great essay on programmers and what they should know about memory (see below), so I'm wondering if someone has put together something similar for networking.
What every programmer should know about memory
|
Some bullet points off the top of my head of things you should know:
How and why TCP works... 3-way handshakes, acknowledgement, delayed ack, nagling, sliding window protocol. There's a concrete reason for every one of those features... and they can all destroy your application's performance if handled improperly.
UDP multicast... even if you never think you'll use it, you need to know why it exists so you can make educated decisions when designing systems.
IP fragmentation, and the impact of MTU.
Binary serialization and network byte ordering (even if you're just going to use Google proto buffers, it's nice to understand why they are efficient).
Ascii serialization and message framing (what does \r\n\r\n mean in HTTP?)
Different I/O dispatch models: Apache-style preforking, thread-per-connection, event-based single-threaded, event-based with worker threads, etc.
The impact of buffer-overflow vulnerabilities in a networked app
Protocol-based design, as opposed to API- or library-based design
asynchronous vs synchronous protocols. Many high-performance systems are asynchronous. HTTP is synchronous unless you use pipelining, and even then, there are many restrictions on what is possible... no out-of-order responses, for example.
Update: What does protocol-based design mean?
Consider HTTP, the protocol of the web. Apache, IIS, Lighttpd, Firefox, Opera, WebKit, etc... All of these pieces of software speak HTTP. It's quite possible that none of them are sharing the code to do so. The downside, of course, is the increased likelihood of bugs due to the net volume of code. There are numerous upsides:
Any program can communicate via HTTP, regardless of implementation language
Lightweight/embedded environments can pick and choose a subset of the protocol, rather than using the whole thing
It's possible to optimize a protocol handler for particular situations. It's not possible to optimize a library without sacrificing generality.
A variety of different implementations forces library providers to address bugs (rather than just blowing them off because, well, everyone uses the same library).
There is no organizational or contractual burden on users of HTTP, no licensing fees.
When you design a network protocol, you can build yourself several APIs, each tailored towards specific use-cases. Or you can build one, it's up to you. Networked software components can be upgraded independent of each other. Basically, everything you hear that's good about Java/C# Interfaces and C++ abstract classes, but applied at the network layer rather than the programming language layer.
|
366,742
| 366,773
|
Creating an Environment Stack in OpenGL
|
I'd like to create an abstraction in OpenGL of the environment settings(blending, stenciling, depth, etc.) that works like the matrix stack. Push onto the stack, make any changes you need, draw your objects, then pop the stack and go back to the prior settings.
For example, currently you might have drawing code like this:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
//Draw operations
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
But with an environment stack it would look like this:
glPushEnv();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
//Draw operations
glPopEnv();
As I see it there are only 2 ways to do this:
Create my own 'flavor' of each environment setting function and call that. It will in turn update the current EnvStack data structure and call the OpenGL environment function.
Alter the OpenGL environment functions to point to my environment functions, which will again update the current EnvStack data structure and call the original OpenGL environment functions.
So option 1 is obviously much simpler. But I run into a problem if I'm using other peoples code in that I don't necessarily know what changes it's making to the environement and therefor my data structure would be out of sync. And since the whole point is to have a simple method of ensuring the environment settings are correct, this is not cool.
So my question is, in this context, how do I change the functions that the OpenGL environment functions point to?
|
OpenGL already contains this functionality. You want glPushAttrib(GL_ALL_ATTRIB_BITS); and glPopAttrib();. See http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html for more.
|
366,768
| 538,742
|
Convert bitmap to PNG in-memory in C++ (win32)
|
Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.).
I also want to be able to define a transparent color (not alpha channel) for this image.
The GdiPlus solution seems to be limited to images of width divisible by 4. Anything else fails during the call to Save(). Does anyone know the reason for this limitation and how/whether I can work around it?
Update: Bounty
I'm starting a bounty (I really want this to work). I implemented the GDI+ solution, but as I said, it's limited to images with quad width. The bounty will go to anyone who can solve this width issue (without changing the image dimensions), or can offer an alternative non-GDI+ solution that works.
|
I read and write PNGs using libpng and it seems to deal with everthing I throw at it (I've used it in unit-tests with things like 257x255 images and they cause no trouble). I believe the API is flexible enough to not be tied to file I/O (or at least you can override its default behaviour e.g see png_set_write_fn in section on customization)
In practice I always use it via the much cleaner boost::gil PNG IO extension, but unfortunately that takes char* filenames and if you dig into it the png_writer and file_mgr classes in its implementation it seem pretty tied to FILE* (although if you were on Linux a version using fmemopen and in-memory buffers could probably be cooked up quite easily).
|
366,923
| 367,132
|
Need advice on Windows to OS X Port Estimation and cost of dev. on OS X
|
I am a 10year+, C++ linux/windows developer and I have been asked to estimate the effort to port the windows application to OS X.
I haven't developed on OS X before,so I don't know what to expect.
It is a C++/Qt application, so I want to ask: what are the de facto tools like editor, IDE, compiler, make tool, etc ? Which tools are commercial and need to be purchased ?
How much time would it take for me to get used to the environment and be productive ?
Thanks in advance,
Paul
|
As jakber already posted, XCode is the standard IDE for MacOSX, and is free (comes with the install DVD or can be downloaded from apple.
The XCode IDE is quite different from that of Visual Studio, and it seems to me as if it were more familiar to Codewarrior. I don't know if there are any tools to convert VS projects to XCode, but there are tools as CMake where you can describe your project and make it generate both Visual Studio solutions and XCode projects (well, and many more).
It is quite hard to estimate the time it will take a particular person to be productive in an environment, and even more when you don't define how you are used to work. For example, if you used KDevelop, then it is directly available under MacOSX. Also, some people are more dependent than others on the tools the IDE provide (source navigation, for example).
Finally, compiler errors are different in Microsoft compilers and g++ (used both in linux and MacOSX) and you will have to get used to it.
Afterpost:
As an answer to your comment, there are more than one compiler for MacOSX. The standard that comes with the OS is gcc (4.0.1) but you can buy the Intel compiler or other frontends like comeau to gcc.
|
366,955
| 366,969
|
Obtain a std::ostream either from std::cout or std::ofstream(file)
|
how do I bind a std::ostream to either std::cout or to an std::ofstream object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following:
std::ostream out = condition ? &std::cout : std::ofstream(filename);
I've seen some examples that are not exception-safe, such as one from http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html:
int main(int argc, char *argv[])
{
std::ostream* fp; //1
if (argc > 1)
fp = new std::ofstream(argv[1]); //2
else
fp = &std::cout //3
*fp << "Hello world!" << std::endl; //4
if (fp!=&std::cout)
delete fp;
}
Does anyone know a better, exception-safe solution?
|
std::streambuf * buf;
std::ofstream of;
if(!condition) {
of.open("file.txt");
buf = of.rdbuf();
} else {
buf = std::cout.rdbuf();
}
std::ostream out(buf);
That associates the underlying streambuf of either cout or the output file stream to out. After that you can write to "out" and it will end up in the right destination. If you just want that everything going to std::cout goes into a file, you can aswell do
std::ofstream file("file.txt");
std::streambuf * old = std::cout.rdbuf(file.rdbuf());
// do here output to std::cout
std::cout.rdbuf(old); // restore
This second method has the drawback that it's not exception safe. You possibly want to write a class that does this using RAII:
struct opiped {
opiped(std::streambuf * buf, std::ostream & os)
:os(os), old_buf(os.rdbuf(buf)) { }
~opiped() { os.rdbuf(old_buf); }
std::ostream& os;
std::streambuf * old_buf;
};
int main() {
// or: std::filebuf of;
// of.open("file.txt", std::ios_base::out);
std::ofstream of("file.txt");
{
// or: opiped raii(&of, std::cout);
opiped raii(of.rdbuf(), std::cout);
std::cout << "going into file" << std::endl;
}
std::cout << "going on screen" << std::endl;
}
Now, whatever happens, std::cout is in clean state.
|
367,310
| 395,962
|
Dynamic Memory Allocation Failure Recovery
|
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user.
Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask.
char someArr[];
do{
someArr = new char[10];
Sleep(100); // no justification for choosing 100 ms
} while ( someArr == NULL );
Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere?
FINAL UPDATE: Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
|
There are a few different ways to attack this - note that the tool instructions will vary a bit, based on what version of Windows CE / Windows Mobile you are using.
Some questions to answer:
1. Is your application leaking memory, leading to this low memory condition?
2. Does your application simply use too much memory at certain stages, leading to this low memory condition?
1 and 2 can be investigated using the Windows CE AppVerifier tool, which can provide detailed memory logging tools for your product. Other heap wrapping tools can also provide similar information (and may be higher-performance), depending on your product design.
http://msdn.microsoft.com/en-us/library/aa446904.aspx
3. Are you allocating and freeing memory very frequently in this process?
Windows CE, prior to OS version 6.0 (don't confuse with Windows Mobile 6.x) had a 32MB / process virtual memory limit, which tends to cause lots of fun fragmentation issues. In this case, even if you have sufficient physical memory free, you might be running out of virtual memory. Use of custom block allocators is usually a mitigation for this problem.
4. Are you allocating very large blocks of memory? (> 2MB)
Related to 3, you could just be exhausting the process virtual memory space. There are tricks, somewhat dependent on OS version, to allocate memory in a shared VM space, outside the process space. If you are running out of VM, but not physical RAM, this could help.
5. Are you using large numbers of DLLs?
Also related to 3, Depending on OS version, DLLs may also reduce total available VM very quickly.
Further jumping off points:
Overview of CE memory tools
http://blogs.msdn.com/ce_base/archive/2006/01/11/511883.aspx
Target control window 'mi' tool
http://msdn.microsoft.com/en-us/library/aa450013.aspx
|
367,633
| 367,662
|
What are all the common undefined behaviours that a C++ programmer should know about?
|
What are all the common undefined behaviours that a C++ programmer should know about?
Say, like:
a[i] = i++;
|
Pointer
Dereferencing a NULL pointer
Dereferencing a pointer returned by a "new" allocation of size zero
Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects)
Dereferencing a pointer that has not yet been definitely initialized
Performing pointer arithmetic that yields a result outside the boundaries (either above or below) of an array.
Dereferencing the pointer at a location beyond the end of an array.
Converting pointers to objects of incompatible types
Using memcpy to copy overlapping buffers.
Buffer overflows
Reading or writing to an object or array at an offset that is negative, or beyond the size of that object (stack/heap overflow)
Integer Overflows
Signed integer overflow
Evaluating an expression that is not mathematically defined
Left-shifting values by a negative amount (right shifts by negative amounts are implementation defined)
Shifting values by an amount greater than or equal to the number of bits in the number (e.g. int64_t i = 1; i <<= 72 is undefined)
Types, Cast and Const
Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast)
Using an automatic variable before it has been definitely assigned (e.g., int i; i++; cout << i;)
Using the value of any object of type other than volatile or sig_atomic_t at the receipt of a signal
Attempting to modify a string literal or any other const object during its lifetime
Concatenating a narrow with a wide string literal during preprocessing
Function and Template
Not returning a value from a value-returning function (directly or by flowing off from a try-block)
Multiple different definitions for the same entity (class, template, enumeration, inline function, static member function, etc.)
Infinite recursion in the instantiation of templates
Calling a function using different parameters or linkage to the parameters and linkage that the function is defined as using.
OOP
Cascading destructions of objects with static storage duration
The result of assigning to partially overlapping objects
Recursively re-entering a function during the initialization of its static objects
Making virtual function calls to pure virtual functions of an object from its constructor or destructor
Referring to nonstatic members of objects that have not been constructed or have already been destructed
Source file and Preprocessing
A non-empty source file that doesn't end with a newline, or ends with a backslash (prior to C++11)
A backslash followed by a character that is not part of the specified escape codes in a character or string constant (this is implementation-defined in C++11).
Exceeding implementation limits (number of nested blocks, number of functions in a program, available stack space ...)
Preprocessor numeric values that can't be represented by a long int
Preprocessing directive on the left side of a function-like macro definition
Dynamically generating the defined token in a #if expression
To be classified
Calling exit during the destruction of a program with static storage duration
|
367,819
| 368,050
|
enum-int casting: operator or function
|
In the external code that I am using there is enum:
enum En {VALUE_A, VALUE_B, VALUE_C};
In another external code that I am using there are 3 #define directives:
#define ValA 5
#define ValB 6
#define ValC 7
Many times I have int X which is equal to ValA or ValB or ValC, and I have to cast it to the corresponding value of En (ValA to VALUE_A, ValB to VALUEB, etc) because some function signature has enum En. And many times I have to do the opposite operation, translate enum En to ValA or ValB or ValC. I cannot change the signatures of these functions, and there are many such functions.
The question is: How to do the translation? Should I create 2 cast operators, which will be used implicitly? Or should I just have 2 translation functions which will be used explicitly:
En ToEn(int)
int FromEn(En)
Or any other solution?
|
Since you can't just cast here, I would use a free function, and if there are likely to be other enums that also need converting, try to make it look a little bit like the builtin casts:
template<typename T>
T my_enum_convert(int);
template<>
En my_enum_convert<En>(int in) {
switch(in) {
case ValA: return VALUE_A;
case ValB: return VALUE_B;
case ValC: return VALUE_C;
default: throw std::logic_error(__FILE__ ": enum En out of range");
}
}
int my_enum_convert(En in) {
switch(in) {
case VALUE_A: return ValA;
case VALUE_B: return ValB;
case VALUE_C: return ValC;
// no default, so that GCC will warn us if we've forgotten a case
}
}
En enumValue = my_enum_convert<En>(ValA);
int hashDefineValue = my_enum_convert(VALUE_A);
enumValue = my_enum_convert<En>(0); // throws exception
Or something like that - might adjust it if issues arise while using it.
The reason I wouldn't use implicit conversion is that there already is an implicit conversion from En to int, which gives the wrong answer. Even if you can reliably replace that with something which gives the right answer, the resulting code won't look as though it's doing any conversion. IMO this will hinder anyone who later looks at the code more than typing a call to a conversion routine will hinder you.
If you want converting to int and converting from int to look very different, then you could give the template and the function above different names.
Alternatively, if you want them to look the same (and more like a static_cast), you could do:
template<typename T>
T my_enum_convert(En in) {
switch(in) {
case VALUE_A: return ValA;
case VALUE_B: return ValB;
case VALUE_C: return ValC;
}
}
int hashDefineValue = my_enum_convert<int>(VALUE_A);
As written, T must have an implicit conversion from int. If you want to support T that only has an explicit conversion, use "return T(ValA);" instead (or "return static_cast<T>(ValA);", if you consider that single-arg constructors are C-style casts and hence impermissible).
|
367,824
| 371,474
|
Using Win32 API in Qt OSE project
|
It is a messy question, hopefully you can figure out what I want :)
What is the best way to use Win32 functionality in a Qt Open Source Edition project?
Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenient and cumbersome.
So, should I separate the Win32 stuff into a library or is there a sensible way of combining these two? Or have I just overlooked some Qt aspect that simplifies this?
EDIT
Removed the syntax stuff, its not really relevant, just annoying.
|
You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide the platform specific data in a private implementation. Trolltech has typically employed the pimpl idiom to accomplish such tasks. So, take a look at the Qt source code to see examples (i.e. look for the "d" pointers).
|
367,926
| 370,538
|
Use a dll from a c++ program. (borland c++ builder and in general)
|
I'm trying to use a dll, namely libcurl, with my program, but, it's not linking. Libcurl comes with .h files that I can include (takes care of dllimport), but then I guess I must specify which dll to actually use when linking somehow... How do I do that? I'm compiling with Borland C++ builder, but I really want to know how these things work in general...
EDIT:
This is the code (straight c/p from curl homepage)
bool FTPGetFile::ConnectToFTP(string ftpServer){
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
return true;
}else{
return false;
}
}
And here are the errors:
[Linker Error] Error: Unresolved external '_curl_easy_init' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
[Linker Error] Error: Unresolved external '_curl_easy_setopt' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
[Linker Error] Error: Unresolved external '_curl_easy_perform' referenced from C:\PROJECTS\PC\TOOLBOX\DEBUG_BUILD\FTPGETFILE.OBJ
EDIT 2: As per suggestion from joe_muc I have made the lib files with the implib tool and included them in the linker path. I still get the same errors.
|
As mentioned, you will need the static .lib file that goes with the .dll which you run
through implib and add the result lib file to your project.
If you have done that then:
You may need to use the stdcall calling convention.
You didn't mention which version of Builder you are using, but
it is usually under Project options - Advanced compiler - Calling convention.
You may need to enable MFC compatibility option.
It could be a name mangling issue (Project options - C++ compatiblity options).
Or generation underscores
Or advanced linker options "Case_insensitive-link" on or off
libcurl appears to be C code; but if it is C++, note that Microsoft and Borland classes are generally not compatible. There are supposed to be tricks to get them to work, but it is a real mess to deal with and I have never had success. C coded DLLs should work.
|
367,984
| 367,990
|
What C++ HTTP frameworks are available?
|
What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application?
|
Well, gSOAP of course. :)
http://www.cs.fsu.edu/~engelen/soap.html
|
368,184
| 368,284
|
Does it make sense to catch exceptions in the main(...)?
|
I found some code in a project which looks like that :
int main(int argc, char *argv[])
{
// some stuff
try {
theApp.Run();
} catch (std::exception& exc) {
cerr << exc.what() << std::endl;
exit(EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
I don't understand why the exceptions are being catched. If they weren't, the application would simply exit and the exception would be printed.
Do you see any good reason to catch exceptions here ?
EDIT : I agree that it is good to print the exception error. However, wouldn't it be better to rethrow the exception ? I have the feeling that we are swallowing it here...
|
If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called.
So, if you aren't running under the debugger, it's probably wise to catch everything: (...) as well as std::exception. Then your application code can clean up with RAII even on a fatal exception. In many such cases you don't actually need to clean up, since the OS will do it for you. But for instance you might prefer to disconnect cleanly from remote services where possible, and there might be resources external to the process, such as named pipes/mutexes, that you'd prefer to destroy rather than leaking.
Rethrowing the exception in main seems to me of limited use, since you've already lost the context in which it was originally thrown. I suppose that trapping an uncaught exception in the debugger is noisier than just logging the fault to std::cerr, so rethrowing would be the smart move if there's a chance of missing the logging.
If you want the debugger to trap unexpected conditions in debug mode, which in release mode throw an exception that eventually results in an exit, then there are other ways to do that than leaving the exception uncaught so that the debugger sees it. For example, you could use assert macros. Of course, that doesn't help with unexpected and unpredictable conditions, like hardware exceptions if you're using SEH on .NET.
|
368,262
| 370,228
|
Function call jumps to the wrong function
|
I am compiling a c++ static library in vs2008, and in the solution i also have a startup project that uses the lib, and that works fine.
But when using the lib in another solution i get an run-time check failure.
"The value of ESP was not properly saved across a functioncall"
Stepping through the code i noticed a function foo() jumping to bar() instead right before the crash. The functions in question are just regular functions and no function pointers.
Anyone has any clue what might be going on, and why it works when using the lib's from the same solution?
edit: the functions (methods) are part of a class, if that helps.
|
Forgive me for stating the bleeding obvious here, but... I've seen this sort of thing happen many times before when object (.o) and header (.h) files get out of sync. Especially with respect to virtual methods.
Consider: The object file is compiled with header:
class Foo { virtual void f(); };
But then the header gets changed to:
class Foo { virtual void g(); virtual void f(); };
And for the next object file, the compiler's assumptions about where f() is located in the class's vtable are incorrect.
Oftentimes simply recompiling the world (everything!) will help.
|
368,737
| 368,810
|
c++ deduction of "non type pointer to function" class template parameters
|
Consider a template class like:
template<typename ReturnType, ReturnType Fn()>
class Proxy
{
void run()
{
ReturnType ret = Fn();
// ... do something ...
}
};
// and a functions
int fn1() { return 5; }
float fn2() { return 5; }
This can be instantiated by using:
Proxy<int, &fn1> p1;
But explicitly declaring the return value type seems needless. What I am trying to achieve is something like:
someProxyInstantation<&fn1> p1;
someProxyInstantation<&fn2> p2;
Unfortunately, I'm no c++ expect and this seems like a hidden corner of the language (at least for me).
If I could just get from the pointer to the function to its type - something like:
std::tr1::result_of<&fn>::type // Error 1 error C2923: 'std::tr1::result_of' : 'fn1' is not a valid template type argument for parameter '_Fty'
the error makes sense since the parameter is not a "type" at all
C++0x has the decltype(&fn1) but that is years away.
Any way of doing this in C++03 (+ tr1)?
Restrictions:
- I don't want to pass the functor, f1 and f2 have to remain global functions that have a return value (can't move it to parameter).)
|
This isn't possible in C++03. If you want to pass a function pointer as a non-type parameter, the compiler has to know the type of the parameter. So you have to provide the missing pieces (in this case, the return type). You can give the proxy the function pointer as a value at runtime, and provide it with the type of it as the only argument. Then you could write a generator function for you that does this job:
template<typename T>
Proxy<T> make_proxy(T t) { return Proxy<T>(t); }
Sadly, in current C++, you still have to give it the type in order to assign to a automatic variable:
Proxy<int(*)()> p = make_proxy(&fn1);
You can't use auto p = make_proxy(&fn1); yet. Note that if you want to use a function type on the left side, you have to change the generator function to provide not a function pointer type:
template<typename T>
Proxy<typename boost::remove_pointer<T>::type> make_proxy(T t) {
return Proxy<typename boost::remove_pointer<T>::type>(t);
}
Now you can do
Proxy<int()> p = make_proxy(&fn1);
using the proxy, you can now just do
doSomething(make_proxy(&fn1));
And if doSomething is templated or otherwise polymorphic, it will not require you to know the exact type of the function.
|
368,963
| 368,974
|
Symbian C++ - Persistent storage of a single variable
|
I wish to store a single variable in my application that will be saved between runs. This will be a version number that will be used to trigger an update option and so will change only rarely.
Does anyone have suggestions on the best way of implementing this? Considering it's such a simple requirement I am interested in the simplest solution.
Thanks!
|
Normally, that sort of information will be held in a constant (not a variable) in the binary, and the binary will contact an external site to find out whether there is a more recent version of the software. When it downloads the new, the newly downloaded file will have a new constant embedded in it.
Alternatively, you could keep the information in some sort of file in the file system. I'm not familiar with the Symbian environment, but something similar most likely exists.
|
368,976
| 368,984
|
How to allocate memory to an array of instances using an abstract class?
|
I have an abstract class defining a pure virtual method in c++:
class Base
{
Base();
~Base();
virtual bool Test() = 0;
};
I have subclassed this with a number of other classes (which provide an implementation for Test()), which I'll refer to as A, B, C, etc. I now want to create an array of any of these types using this base class:
int main(int argc, char* argv[])
{
int size = 0;
Base* bases = new Base[10];
bases[size++] = new A();
bases[size++] = new B();
for (int i = 0; i < size; i++)
{
Base* base = bases[i];
base->Test();
}
}
(Excuse any errors I might have made, I'm writing this on the fly to provide a simple example).
The problem is I can't instantiate the array as it would require creating an instance of the Base class (which it can't do as it's abstract). However, without doing this, it hasn't allocated the memory needed to assign to the indices of the array, and thus provides a segmentation fault when trying to access that memory. I am under the impression that it's not good practice to mix new and delete with malloc and free.
It may be that I have confused the way this should be used and I should be attempting to use templates or some other mechanism to do this, but hopefully I've provided enough information to illustrate what I'm attempting to do.
So what is the best way of doing this and how would I get around this problem of allocating memory to an abstract class?
Thanks,
Dan
|
There is only a slight misunderstanding in that code. Instead of allocating Base objects, you have to allocate pointers. A pointer can exist at any time. A pointer to a abstract class, to an incomplete type, and even to void is valid:
int main(int argc, char* argv[])
{
int size = 0;
Base** bases = new Base*[10];
bases[size++] = new A();
bases[size++] = new B();
for (int i = 0; i < size; i++)
{
Base* base = bases[i];
base->Test();
}
}
|
369,211
| 369,276
|
What function in the std library is there to binary search a vector and find an element?
|
I've got a node struct
struct Node{CString text, int id;};
in a sorted vector.
I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element.
|
std::binary_search() will tell you if a value exists in the container.
std::lower_bound()/std::upper_bound() will return an iterator to the first/last occurrence of a value.
Your objects need to implement operator< for these algorithms to work.
|
369,506
| 369,513
|
./ changes target when i use OpenFileDialog
|
I'm using a streamwriter to log errors
the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt"
Everything works correctly, but after I use an open file dialog to say, "C:\home\myfolder\myfile" the streamwriter tries to write to "c:\home\myfolder\logs[current-date].txt"
I know solutions to this problem but i just dont understand what's going on
|
The current directory is a process wide value.
The OpenFileDialog is changing the current directory.
If you're using the .NET OpenFileDialog class, you can set the RestoreDirectory property to true to tell the dialog to leave the current directory alone (although the way the docs for RestoreDirectory is written there may be some threading issues, which I imagine might make this still inappropriate for a logging facility).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.