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
|
|---|---|---|---|---|
281,045
| 281,082
|
Do class/struct members always get created in memory in the order they were declared?
|
This is a question that was sparked by Rob Walker's answer here.
Suppose I declare a class/struct like so:
struct
{
char A;
int B;
char C;
int D;
};
Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I had always assumed that the compiler can do whatever it wants with them.
This leads into my next question. If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:
struct
{
char A;
char C;
int B;
int D;
};
(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)
Related topics
Why doesn't GCC optimize structs?
|
C99 §6.7.2.1 clause 13 states:
Within a structure object, the
non-bit-field members and the units in
which bit-fields reside have addresses
that increase in the order in which
they are declared.
and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1.
C++ is a bit more complicated. In the 1998 and 2003 standards, there is §9.2 clause 12 (clause 15 in C++11):
Nonstatic data members of a
(non-union) class declared without an
intervening access-specifier are
allocated so that later members have
higher addresses within a class
object. The order of allocation of
nonstatic data members separated by an
access-specifier is unspecified
(11.1). Implementation alignment
requirements might cause two adjacent
members not to be allocated
immediately after each other; so might
requirements for space for managing
virtual functions (10.3) and virtual
base classes (10.1).
|
281,060
| 281,822
|
Win32 WriteProcessMemory() magical offset value
|
I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "magic" value that I got lucky with and picked at random during a moment of frustration, the call works on my system, but fails on other ones. (see the code below)
Can anybody suggest what this magical offset is doing for me? By trial and error, I can find values that work on specific systems, but I can't find a general solution to this problem.
Thanks,
PaulH
#define MAGIC_OFFSET (DWORD)0x01020000
LVHITTESTINFO hti = { 0 };
hti.pt = clientPoint;
LPVOID lpBuffer = ::VirtualAlloc( NULL, 1, MEM_RESERVE, PAGE_READWRITE );
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
lpBuffer = ::VirtualAlloc( (LPVOID)((DWORD)lpBuffer + MAGIC_OFFSET), sizeof( hti ), MEM_RESERVER, PAGE_READWRITE );
DWORD dwBuffer = (DWORD)lpBuffer + MAGIC_OFFSET - sizeof( hti );
if( !::WriteProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
if( ListView_HitTest( hWndListView, (LPVOID)dwBuffer ) < 0 )
return 0;
if( !::ReadProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
Clarification (added by Cd-MaN): this is on a Windows Mobile platform, probably non-x86 architecture. So the situation may be different (are there separate address spaces in ARM processors?).
|
Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of shared memory, and I did a quick check to make sure these functions are supported by Windows Mobile 5.
|
281,136
| 281,266
|
Creating an object in shared memory inside a Shared Lib (so) in C++
|
Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?
god* _god = NULL;
extern "C"
{
int set_log_level(int level)
{
if(_god == NULL) return -1;
_stb->log_level(level);
return 0;
}
int god_init(){
if(_god == NULL){
_god = new god(); //Magic happens here
}
}
}
Provided that I perform a lock synchronization at the beginning of every function, and considering that God itself can new/malloc other things, but those things will never be returned themselves to the caller (God mallocs only for internal use), what is the simplest way of doing this, if possible.
How can that be extended to an arbitrary number of programs linked to this shared library?
|
Boost Interprocess library has high(er) level, portable shared memory objects.
|
281,260
| 281,379
|
RGB back buffer in Win32
|
I have an array of RGB values, whose size I can guarantee to match the client area of a window on screen.
Using the Win32 API, what are the easiest and fastest ways to get the contents of my array on the screen in response to a WM_PAINT message?
If it makes it simpler/faster, we can assume it's a 32-bit display and each element of the array is 32 bits.
|
If you have complete control over your backing format, use a DIB format and a dummy BITMAPINFO structure. Then use SetDIBitsToDevice to copy to the DC.
Be aware of the peculiarities of the DIB format - every line has to be extended to a multiple of 4 bytes, the first line of the buffer is the bottom line of the image, and the byte order is Blue,Green,Red.
|
281,275
| 281,296
|
Best way to merge multiple STL containers, removing duplicate elements?
|
I have two STL containers that I want to merge, removing any elements that appear more than once. For example:
typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
// c3 now contains the following 4 elements:
// 1, 2, 3, 4
std::unique seems to be for adjacent elements only, and in my case the containers could be in any order. I could do some std::set trickery I guess:
container unique_merge(const container& c1, const container& c2)
{
std::set<container::value_type> s;
BOOST_FOREACH(const container::value_type& val, c1)
s.insert(val);
BOOST_FOREACH(const container::value_type& val, c2)
s.insert(val);
return container(s.begin(), s.end());
}
Is there a better way or have I missed something bleeding obvious?
|
For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N*log n).
The other option is to run std::sort on each list individually and then walk through them in parallel using std::set_union, which removes duplicates for you. This will also be O(n*log n), so if you're worried about performance, you'll have to profile. If you're not, do whichever makes more sense to you.
Edit:
set_union will only work if there are no duplicates in the original lists, otherwise you'll have to go with sort, merge, unique and erase. The big O performance is still the same, with the same caveats about profiling.
template <typename container>
container unique_merge(container c1, container c2)
{
std::sort(c1.begin(), c1.end());
std::sort(c2.begin(), c2.end());
container mergeTarget;
std::merge(c1.begin(), c1.end(), c2.begin(), c2.end(),
std::insert_iterator(mergeTarget, mergeTarget.end())
);
std::erase(
std::unique(mergeTarget.begin(), mergeTarget.end()),
mergeTarget.end()
);
return mergeTarget;
}
|
281,365
| 281,385
|
Does myVector.erase(myPtr) delete the object pointed by myPtr?
|
If I have the following code,
Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
Did I create a memory leak?
I guess so, but the word erase gives the feeling that it is deleting it.
Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?
|
Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.
It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:
{
boost::shared_ptr<foo> f(new foo);
std::vector< boost::shared_ptr<foo> > v;
v.push_back(f);
v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */
The next C++ standard (called C++1x and C++0x commonly) will include std::shared_ptr. There, you will also be able to use std::unique_ptr<T> which is faster, as it doesn't allow copying. Using std::unique_ptr with containers in c++0x is similar to the ptr_container library in boost.
|
281,445
| 281,502
|
Namespacing (static) member variables
|
I would like to be able to achieve something like this:
class Zot
{
namespace A
{
static int x;
static int y;
}
}
I am working with a legacy system that uses code generation heavily off a DB schema, and certain fields are exposed as methods/variables in the class definition. I need to add a few extra static variables to these classes and would like to guarantee no clashes with the existing names.
The best I have come up with is to use another struct to wrap the statics as if it were a namespace:
class Zot
{
struct A
{
static int x;
static int y;
}
}
Is there a better way?
Update:
An extra requirement is to be able to access these from a template elsewhere
e.g.
template<class T>
class B
{
void foo() { return T::A::x; }
};
So putting them in a separate class won't work
|
Really the inner struct is your best bet. Another possibility would be to use a typedef to bring in a class of statics. This works well for code generation in that you can separate the extras from the generated code:
In the generated file that doesn't care at all what's in Zot_statics:
class Zot_statics;
class Zot
{
public:
typedef Zot_statics A;
int x; // This is ok
};
In a hand-maintained header for when you need to access x and y:
class Zot_statics
{
public:
static int x;
static int y;
};
In a hand-maintained cpp file:
int Zot_statics::x;
int Zot_statics::y;
And your template should work just fine with Zot::X referring to the instance variable X on Zot, and Zot::A::x refering to the static variable.
|
281,698
| 281,707
|
What is wrong with this inheritance?
|
I just don't get it. Tried on VC++ 2008 and G++ 4.3.2
#include <map>
class A : public std::multimap<int, bool>
{
public:
size_type erase(int k, bool v)
{
return erase(k); // <- this fails; had to change to __super::erase(k)
}
};
int main()
{
A a;
a.erase(0, false);
a.erase(0); // <- fails. can't find base class' function?!
return 0;
}
|
When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should stop looking for the function you are trying to call once it finds the first match. After finding the function by name, then it applies the overload resolution rules.
So what is happening is the compiler finds your implementation of erase(int, bool) when you call erase(0), and then decides that the arguments don't match.
|
281,725
| 281,830
|
Template specialization based on inherit class
|
I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.
-edit-
I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.
class SomeTag {};
class InheritSomeTag : public SomeTag {};
template <class T, class Tag=T>
struct MyClass
{
};
template <class T>
struct MyClass<T, SomeTag>
{
typedef int isSpecialized;
};
int main()
{
MyClass<SomeTag>::isSpecialized test1; //ok
MyClass<InheritSomeTag>::isSpecialized test2; //how do i make this specialized w/o changing main()
return 0;
}
|
This article describes a neat trick: http://www.gotw.ca/publications/mxc++-item-4.htm
Here's the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking):
template<typename D, typename B>
class IsDerivedFrom
{
class No { };
class Yes { No no[3]; };
static Yes Test( B* ); // not defined
static No Test( ... ); // not defined
static void Constraints(D* p) { B* pb = p; pb = p; }
public:
enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
IsDerivedFrom() { void(*p)(D*) = Constraints; }
};
Then your MyClass needs an implementation that's potentially specialized:
template<typename T, int>
class MyClassImpl
{
// general case: T is not derived from SomeTag
};
template<typename T>
class MyClassImpl<T, 1>
{
// T is derived from SomeTag
public:
typedef int isSpecialized;
};
and MyClass actually looks like:
template<typename T>
class MyClass: public MyClassImpl<T, IsDerivedFrom<T, SomeTag>::Is>
{
};
Then your main will be fine the way it is:
int main()
{
MyClass<SomeTag>::isSpecialized test1; //ok
MyClass<InheritSomeTag>::isSpecialized test2; //ok also
return 0;
}
|
281,787
| 281,807
|
Best way to take a snapshot of an object to a file
|
What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?
Contrived example:
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container,
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"
Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.
|
Take a look at this library .
|
281,818
| 4,541,470
|
Unmangling the result of std::type_info::name
|
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<int>).name() returns St6vectorIiSaIiEE.
Is there a way to produce something useful from this? Like std::vector<int> for the above example. If it only works for non-template classes, that's fine too.
The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
|
Given the attention this question / answer receives, and the valuable feedback from GManNickG, I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.
In file type.hpp
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std::string demangle(const char* name);
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
#endif
In file type.cpp (requires C++11)
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
// enable c++11 by passing the flag -std=c++11 to g++
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return (status==0) ? res.get() : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
Usage:
#include <iostream>
#include "type.hpp"
struct Base { virtual ~Base() {} };
struct Derived : public Base { };
int main() {
Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code!
std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl;
std::cout << "Type of pointee: " << type(*ptr_base) << std::endl;
delete ptr_base;
}
It prints:
Type of ptr_base: Base*
Type of pointee: Derived
Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2).
If you cannot use C++11 features, here is how it can be done in C++98, the file type.cpp is now:
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
struct handle {
char* p;
handle(char* ptr) : p(ptr) { }
~handle() { std::free(p); }
};
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );
return (status==0) ? result.p : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
(Update from Sep 8, 2013)
The accepted answer (as of Sep 7, 2013), when the call to abi::__cxa_demangle() is successful, returns a pointer to a local, stack allocated array... ouch!
Also note that if you provide a buffer, abi::__cxa_demangle() assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): "If output_buffer is not long enough, it is expanded using realloc." Calling realloc() on a pointer to the stack... ouch! (See also Igor Skochinsky's kind comment.)
You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name not longer than 15 (so realloc() is not called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash.
To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call realloc() with a pointer to the stack.
(The old answer from Dec 27, 2010)
Important changes made to KeithB's code: the buffer has to be either allocated by malloc or specified as NULL. Do NOT allocate it on the stack.
It's wise to check that status as well.
I failed to find HAVE_CXA_DEMANGLE. I check __GNUG__ although that does not guarantee that the code will even compile. Anyone has a better idea?
#include <cxxabi.h>
const string demangle(const char* name) {
int status = -4;
char* res = abi::__cxa_demangle(name, NULL, NULL, &status);
const char* const demangled_name = (status==0)?res:name;
string ret_val(demangled_name);
free(res);
return ret_val;
}
|
282,016
| 282,560
|
Using C++ COM interface in C# for both client and server
|
I need to make a piece of C# code interact through COM with all kinds of implementations.
To make it easeier for users of that integration, I included the interacted interfaces in IDL (as part of a relevant existing DLL, but without coclass or implementation), then got that into my C# code by running Tlbimp to create the types definition.
I implemented my C#, creating COM objects based on Windows registry info and casting the object into the interface I need.
I then created a C# implementation of the interface in a seperate project and registered it.
The main program creates the testing COM object correctly but fails to cast it into the interface (gets a null object when using C# 'as', gets an InvalidCastException of explicit cast).
Can someone suggest why the interface is not identified as implemented by the testing object?
This is the interface defition in IDL (compiled in C++ in VS 2005):
[
object,
uuid(B60C546F-EE91-48a2-A352-CFC36E613CB7),
dual,
nonextensible,
helpstring("IScriptGenerator Interface"),
pointer_default(unique)
]
interface IScriptGenerator : IDispatch{
[helpstring("Init the Script generator")]
HRESULT Init();
[helpstring("General purpose error reporting")]
HRESULT GetLastError([out] BSTR *Error);
};
This is the stub created for C# by Tlbimp:
[TypeLibType(4288)]
[Guid("B60C546F-EE91-48A2-A352-CFC36E613CB7")]
public interface IScriptGenerator
{
[DispId(1610743813)]
void GetLastError(out string Error);
[DispId(1610743808)]
void Init();
}
This is part of the main C# code, creating a COM object by its ProgID and casting it to the IScriptGenerator interface:
public ScriptGenerator(string GUID)
{
Type comType = Type.GetTypeFromProgID(GUID);
object comObj = null;
if (comType != null)
{
try
{
comObj = Activator.CreateInstance(comType);
}
catch (Exception ex)
{
Debug.Fail("Cannot create the script generator COM object due to the following exception: " + ex, ex.Message + "\n" + ex.StackTrace);
throw ex;
}
}
else
throw new ArgumentException("The GUID does not match a registetred COM object", "GUID");
m_internalGenerator = comObj as IScriptGenerator;
if (m_internalGenerator == null)
{
Debug.Fail("The script generator doesn't support the required interface - IScriptGenerator");
throw new InvalidCastException("The script generator with the GUID " + GUID + " doesn't support the required interface - IScriptGenerator");
}
}
And this is the implementing C# code, to test it's working (and it's not):
[Guid("EB46E31F-0961-4179-8A56-3895DDF2884E"),
ProgId("ScriptGeneratorExample.ScriptGenerator"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(SOAAPIOLELib.IScriptGeneratorCallback))]
public class ScriptGenerator : IScriptGenerator
{
public void GetLastError(out string Error)
{
throw new NotImplementedException();
}
public void Init()
{
// nothing to do
}
}
|
Again - thanks for the suggestions.
I was able to finally resolve the issue on my own. I tried the above suggestions and didn't made any progress. Then I changed the namespace of the interop in the 'testing' code - it varied from the one in the main code because of different argument use when using Tlbimp. This solved the problem.
Here's my guess to why: .Net creates the COM object, but when it detects this is actually a .Net object, it bypass the COM layer and communicates directly. In which case, queryInterface (with the interface GUID) is not used and the interface do differ because of different C# namespaces.
This means that in order to supprot integration with .Net code, I will need to publish my original interop assembly aside the IDL.
Thanks,
Inbar
|
282,091
| 282,442
|
Set OLE Request Timeout from C++
|
I am instantiating a local COM server using CoCreateInstance. Sometimes the application providing the server takes a long time to start. When this happens, Windows pops a dialog box like this:
Server Busy
The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy program and correct the problem.
[Switch To...] [Retry] [Cancel]
I have found mention of a Visual Basic property on the Application object, OleRequestPendingTimeout, that can be used to control the time before this dialog comes up. I can't find any good documentation on this or an equivalent that is useful from C++. Can anyone point me in the right direction?
|
If you're using MFC, we used to do stuff like this:
// prevent the damned "Server Busy" dialog.
AfxOleGetMessageFilter()->EnableBusyDialog(0);
AfxOleGetMessageFilter()->EnableNotRespondingDialog(0);
|
282,176
| 282,190
|
Waitpid equivalent with timeout?
|
Imagine I have a process that starts several child processes. The parent needs to know when a child exits.
I can use waitpid, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in waitpid to exit gracefully and join it. It's nice to have things clean up themselves, but it may not be that big of a deal.
I can use waitpid with WNOHANG, and then sleep for some arbitrary time to prevent a busy wait. However then I can only know if a child has exited every so often. In my case it may not be super critical that I know when a child exits right away, but I'd like to know ASAP...
I can use a signal handler for SIGCHLD, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit.
What I'd really like to do is use waitpid on some timeout, say 5 sec. Since exiting the process isn't a time critical operation, I can lazily signal the thread to exit, while still having it blocked in waitpid the rest of the time, always ready to react. Is there such a call in linux? Of the alternatives, which one is best?
EDIT:
Another method based on the replies would be to block SIGCHLD in all threads with pthread \ _sigmask(). Then in one thread, keep calling sigtimedwait() while looking for SIGCHLD. This means that I can time out on that call and check whether the thread should exit, and if not, remain blocked waiting for the signal. Once a SIGCHLD is delivered to this thread, we can react to it immediately, and in line of the wait thread, without using a signal handler.
|
The function can be interrupted with a signal, so you could set a timer before calling waitpid() and it will exit with an EINTR when the timer signal is raised. Edit: It should be as simple as calling alarm(5) before calling waitpid().
|
282,194
| 282,220
|
How to get memory usage under Windows in C++
|
I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.
|
A good starting point would be GetProcessMemoryInfo, which reports various memory info about the specified process. You can pass GetCurrentProcess() as the process handle in order to get information about the calling process.
Probably the WorkingSetSize member of PROCESS_MEMORY_COUNTERS is the closest match to the Mem Usage coulmn in task manager, but it's not going to be exactly the same. I would experiment with the different values to find the one that's closest to your needs.
|
282,372
| 3,453,616
|
demote boost::function to a plain function pointer
|
want to pass boost::bind to a method expecting a plain function pointer (same signature).
typedef void TriggerProc_type(Variable*,void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)> triggerProc ...
InitVariable(triggerProc);
error C2664: 'InitVariable' : cannot convert parameter 1 from
'boost::function<Signature>' to 'void (__cdecl *)(type *,void *)'
I can avoid storing a boost::function and just pass the bound functor directly, but then I get similar error:
error C2664: 'blah(void (__cdecl *)(type *,void *))' : cannot convert parameter
1 from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl *)(type *,void *)'
|
Has anyone noticed that the accepted answer only works with trivial cases? The only way that function<>::target() will return an object that can be bound to a C callback, is if it was constructed with an object that can be bound to a C callback. If that's the case, then you could have bound it directly and skipped all of the function<> nonsense to begin with.
If you think about it, there isn't any magic solution to this. A C-style callback is stored as a single pointer which points to executable code. Any nontrivial boost::function<> is going to need at least two pointers: one to the executable code, the other to the data that's needed to set up the call (e.g. the 'this' pointer, in the case of a bound member function).
The right way to use boost::function and boost::bind with C callbacks is to create a shim function that satisfies the callback signature, figures out which function<> to call, and calls it. Usually C callbacks will have some kind of a void* for 'user data'; that's where you stash your function pointer:
typedef void (*CallbackType)(int x, void* user_data);
void RegisterCallback(CallbackType cb, void* user_data);
void MyCallback(int x, void* userData) {
boost::function<void(int)> pfn = static_cast<boost::function<void(int)> >(userData);
pfn(x);
}
boost::function<void(int)> fn = boost::bind(myFunction(5));
RegisterCallback(MyCallback, &fn);
Of course, if your callback signature doesn't include some kind of user data pointer, you're out of luck. But any callback that doesn't include a user data pointer is already unusable in most real-world scenarios, and needs to be rewritten.
|
282,419
| 284,681
|
How to create an alias for a build target with a relative path in Scons?
|
Background
I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects:
Prj1 is an EXE that depends on Prj2
Prj2 is a DLL that exports some functions
You can see the directory structure and the contents of my SConstruct and SConscript files here
Problem
The problem I'm running into is that in order to build these targets from the command line I have to specify both the relative path to their build directory and their platform specific file extensions.
For example, to build Prj1 I have to do:
build> scons ../bin/project1.exe
Likewise, to build Prj2 I have to do:
build> scons ../bin/project2.dll
Question
How can I make SCons build these projects without specifying the relative path and platform specific file extension?
Desired:
build> scons project1
build> scons project2
Potential Solutions
Use Alias - I'm pretty sure this is what I want but I'm messing something up apparently. I've tried the following without success:
prj1_env.Alias( 'project1', PROG)
prj1_env.Alias( 'project1', os.path.join( BIN_DIR, PROG) )
References
How do I get projects to place their build output into the same directory with Scons?
|
Moving this to an answer instead of a comment. :)
References
How
do I get projects to place their
build output into the same directory
with Scons?
Alias needs an actual target as its second argument. I think the issue is that "project1" (the value of PROG) is not an actual target. An easy way to correct this is the following.
Make PrefixProgram return a value:
def PrefixProgram(env, outdir, trgt, srcs):
return env.Program(target = os.path.join(outdir, trgt), source = srcs)
Then:
target = PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES )
prj1_env.Alias("project1", target)
You can of course just do this:
prj1_env.Alias("project1", PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES ))
But I think the first way is easier to understand.
I hope this helps.
|
282,526
| 282,553
|
Commenting out comments
|
I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:
If I have:
/*
int commented_out = 0;
*/
I can comment out the /* and */ with // and code within the /* and */ is no longer "commented out" (the text changes to non-comment color and the compiler treats it as code once again). Like so:
///*
int commented_out = 0;
//*/
I've found this is true for msvc 2003, is this normal C++ behavior or is it just a fluke that works with this compiler?
|
Yep, this is perfectly normal behavior. The C++ standard says that a /* is the start of a comment block only if it itself is not commented out. I often use what you've written above to comment or uncomment a block of code by adding/deleting one character. A nice little trick for switching between two blocks of code, one of which is always commented out is:
//*
code block 1 (uncommented)
/*/
code block 2 (commented)
//*/
Now, delete one slash from the start, and it becomes
/*
code block 1 (commented)
/*/
code block 2 (uncommented)
//*/
Not something to use in production code, but very useful for quick debugging changes.
|
282,570
| 282,573
|
C++ Opening a file and inputting data to a class object
|
Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.
I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user and passed onto the function. Here is my basic read in function:
template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
ifstream myFile;
T object;
myFile.open("inputFile")
while(!myFile.eof())
{
myFile >> object;
insert(v, object, U)
}
}
insert is just another function that will go through and insert the data into my data structure. I just want to make sure this is the best way to pass that data on if it will even work.
|
It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself?
|
282,603
| 282,658
|
C++ compiler optimization of passed arguments
|
I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:
WARN(
"Danger Will Robinson! There are "
+ boost::lexical_cast<string>(minutes)
+ " minutes of oxygen left!"
);
I'm using an inline function for WARN, but I'm curious as to how much optimization is going on behind the scenes -- evaluation of the arguments throughout the entire program would be costly. The WARN function goes something like this:
bool WARNINGS_ENABLED = false;
inline void WARN(const string &message) {
if (!WARNINGS_ENABLED) {
return;
}
// ...
}
Given that constructing the string argument has no side-effects, will the compiler optimize it out? Is a certain level of optimization required (-Ox in g++ for some x)?
|
If you need to be able to selectively enable and disable the warnings at run-time, the compiler will not be able to optimize out the call.
What you need is to rename your function to WARN2 and add a macro something like:
#define WARN(s) do {if (WARNINGS_ENABLED) WARN2(s);} while (false)
This will prevent the evaluation of s at run-time unless you have warnings enabled.
The do-while stuff is a trick that allows it to be used anywhere in the code (naked statement, statement within a braced if-block, statement within an unbraced if-block, braced and unbraced while statements and so on).
|
282,696
| 282,725
|
How to call c++ binary from Perl or PHP (CGI-BIN using Apache on Linux )?
|
I have a website cgi-bin program that is written in c++.
Unfortunately the website provider for my friend's site only allows Perl or PHP cgi-bin scripts.
Is there an easy way to simply have a very small Perl or PHP wrapper that just calls the c++ compiled binary?
Would the c++ program still be able to read from stdin for POST commands or would it have to be read by the Perl or PHP and then forwarded.
|
You can use Perl's backticks or "system" commands to run shell commands. Also, perl has a lot of "Inline" classes that allow you to write code in other languages to be called in perl, including one for C++. If you can't find something that works, maybe you can make your own wrapper using that package.
|
282,700
| 282,717
|
ld: duplicate symbol
|
I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand.
ld output:
ld: duplicate symbol text_field(std::basic_istream >&)in /path/final/build/final.build/Release/final.build/Objects-normal/ppc/generics.o and /path/final/build/final.build/Release/final.build/Objects-normal/ppc/main.o
collect2: ld returned 1 exit status
Below is my file io_functions.cpp This is the only declaration of text_field in the entire project.
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
#ifndef ENDF
#define ENDF '|'
#define ENDR '\n'
/**
reads one field from a given input stream
Usage: var = text_field(in)
*/
string text_field(istream &in){
string s;
getline(in, s, ENDF);
return s;
}
long long_field(istream &in){
return atol(text_field(in).c_str());
}
int int_field(istream &in){
return atoi(text_field(in).c_str());
}
double double_field(istream &in){
return atof(text_field(in).c_str());
}
#endif
What is going wrong? For a number of reasons I don't want to post my project's entire source.
|
My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in main.o and generics.o.
So it looks like you're including the io_functions.cpp file into the main.cpp and generics.cpp which is a bad idea at the best of times.
You should have a header file (e.g., io_functions.h) that specifies everything contained in io_functions.cpp and include that header file into the other two.
|
282,800
| 282,818
|
C++ odd compile error: error: changes meaning of "Object" from class "Object"
|
I don't even know where to go with this. Google wasn't very helpful. As with my previous question. I'm using TextMate's Command+R to compile the project.
game.h:16:error: declaration of ‘Player* HalfSet::Player() const’
players.h:11:error: changes meaning of ‘Player’ from ‘class Player’
game.h:21:error: ‘Player’ is not a type
player.h file (partial)
#ifndef PLAYERS_H
#define PLAYERS_H
using namespace std;
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
#include "generics.h"
class Player{ //Line 11
public:
//getters
long Id() const;
string FirstName() const;
string LastName() const;
string Country() const;
//setters
void setId(long id);
void setFirstName(string s);
void setLastName(string s);
void setCountry(string s);
//serializing functions
void display(ostream &out);
void read(istream &in);
void write(ostream &out);
//Initalizers
Player();
Player(istream &in);
Player(string firstName, string lastName);
Player(string firstName, string lastName, string country);
Player(long id, string firstName, string lastName, string country);
~Player();
private:
long _id;
string _firstName;
string _lastName;
string _country;
};
game.h file (partial)
#ifndef GAME_H
#define GAME_H
#include "generics.h"
#include "players.h"
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
using namespace std;
class HalfSet{
public:
//getters
Player* Player() const; //Line 16
int GamesWon() const;
int TotalPoints() const;
int Errors() const;
//setters
void setPlayer(Player* p);
void setGamesWon(int games);
void setTotalPoints(int points);
void setErrors(int errors);
//Serialization
void display(ostream &out) const;
void read(istream &in) const;
void write(ostream &out) const;
//Initalizers
HalfSet();
~HalfSet();
private:
Player* _player;
int _gamesWon;
int _points;
int _errors;
};
What is going on here?
|
In C++ you cannot name a function the same name as a class/struct/typedef. You have a class named "Player" and so the HalfSet class has a function named "Player" ("Player *Player()"). You need to rename one of these (probably changing HalfSet's Player() to getPlayer() or somesuch).
|
282,966
| 284,871
|
Using Chromium as a MFC CWnd
|
I am looking to using Google Chromium for my MFC app as an HTML renderer. I found this test bed application and I am wondering if anyone knows how or of a resource that I can make sense of it so that I could extract the Webkit/Webview stuff into my application. Thanks.
~/webkit/tools/test_shell
~/webkit/tools/test/reference_build/webkit-release/test_shell.exe
Thanks.
|
#chromium on irc.freenode.net
http://groups.google.com/group/chromium-dev
|
283,042
| 283,611
|
How to pass large struct back and forth between between C++ and Lua
|
I am looking at embedding Lua in a C++ application I am developing. My intention is to use Lua to script what ordered operation(s) to perform for some given input, ie.
receive a new work item in c++ program, pass details to Lua backend, Lua calls back into c++ to carry out necessary work, returns finished results.
The primary data structure involved is a large (approx 80+ members) struct. I am (very) new to Lua and am unsure of how I can pass it to and from my host application and the embedded Lua state.
Thus far I see my options as:
a) Pushing/Popping all the individual data members onto the stack when crossing to/from C++ and Lua (sounds messy).
b) Constructing a table and populating with the values, then putting that on/off the stack (a little cleaner).
c) Pass it as userdata (light/heavy?) (I'm sketchy on this, and not sure if/how I can then access it from the Lua side to query what operations are necessary).
Any guidance would be greatly appreciated.
|
If I recall correctly, light userdata is actually just a pointer. They all share the same metatable. They are mostly used to pass around addresses of C data.
Full userdata is probably closer of what you need if you must access it from the Lua side. Their metatable would allow you to access it like it was a regular Lua table, for example.
You might be also interested by Roberto's library for converting data to and from C structs for Lua 5.1. Or not. Depends on your needs... :-)
|
283,166
| 283,172
|
Easy way to convert a struct tm (expressed in UTC) to time_t type
|
How do I do the above? There is mktime function but that treats the input as expressed in local time but how do i perform the conversion if my input tm variable happens to be in UTC.
|
Use timegm() instead of mktime()
|
283,295
| 283,337
|
SendMessage API in 64 bit
|
According to MSDN
The return value specifies the result
of the message processing; it depends
on the message sent.
I know it is defined as
typedef LONG_PTR LRESULT;
Meaning it will be 8 bytes on 64bit machine but it doesn't!
Does anyone know if it is safe to assume that only the lower 4 bytes are used and store it as an INT (for example).
|
No it's not safe, because the return value is defined by the message being sent and the handler.
If you control the handler and the message then it'd be possible, it's not safe in the general case.
James
|
283,297
| 283,317
|
Return dynamically allocated memory from C++ to C
|
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..
const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
return ss.str().c_str();
}
could the c string be destroyed when ss falls off the stack? I'm assuming so...
Another option may be to create a new string on the heap, but what is going to deallocate that?
const char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
char *out = new char[ss.str().size()];
strcpy(ss.str().c_str(), out);
return out;//is out ever deleted?
}
The same goes for pointers to other things as well as strings.
|
The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.
Next, you can not return a const char* unless you return a pointer to a static string like this:
const char *GetString()
{
return "a static string in DATA segment - no need to delete";
}
You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible.
If you return a string to C, there are 2 way to do that:
char *GetString()
{
std::stringstream ss;
ss << "The random number is: " << rand();
return strdup( ss.str().c_str() ); // allocated in C style with malloc()
}
void foo()
{
char *p = GetString();
printf("string: %s", p));
free( p ); // must not forget to free(), must not use delete()
}
or:
char *GetString(char *buffer, size_t len)
{
std::stringstream ss;
ss << "The random number is: " << rand();
return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory
}
void foo()
{
char buffer[ 100 ];
printf("string: %s", GetString(buffer, sizeof( buffer ))); // no memory leaks
}
depending on you memory handling policy.
As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.
|
283,375
| 283,387
|
Detecting TCP Client Disconnect
|
Let's say I'm running a simple server and have accept()ed a connection from a client.
What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle this?
|
select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected: Stephen Cleary, Detection of Half-Open (Dropped) Connections.
* for Windows use ioctlsocket.
|
283,406
| 283,408
|
What is the difference between atan and atan2 in C++?
|
What is the difference between atan and atan2 in C++?
|
std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.
|
283,450
| 283,475
|
How do you organise your STL headers?
|
I am working on a large project that uses the STL and have a question about your preferred way to organise your STL #includes.
Do you prefer to #include each header in the source file it is used. For example, if both foo.cpp and bar.cpp require std::string, then both will #include <string>.
Do you prefer to have a single header file that includes all the STL headers your project uses (i.e. add them to the MS 'stdafx.h' pre-compiled header).
The advantage of the first method is that the .cpp file is an independent unit and can be used in a different project without having to worry that you're missing a #include. The advantages of the second method is that you can take use your compilers pre-compiled header support plus you can wrap STL #includes in pragmas that disable some warnings (for example, some Boost headers will cause warnings when compiling at level 4).
Which do you prefer to use?
|
I only include the header files that are really needed in every source, and not 'catch all' headers, to keep dependencies (and hence compile times) as low as possible.
Precompiled headers can work irrespective of this (i.e. I rely on precompiled headers to speed up the compiling process, not to get declarations). So even if something gets declared via the included precompiled headers, I still include the 'regular' header, which will get skipped by the include guard mechanism and won't add anything significant to the compile times.
As precompiled headers are a compiler specific thing. Optimizing / changing precompiled headers should have no effect on the correct functioning of the code in my opinion.
The main advantage of having dependencies as low as possible is that refactoring gets easier (or rather: feasible)
Great book on all this is Large Scale C++ Design from Lakos
|
283,593
| 283,624
|
Using C++ from Objective C : how to allocate/deallocate?
|
Currently, my Objective C classes use C++ objects by doing a new when the owner is created, and calling delete when it is destroyed. But is there another way? I'd like to be able to declare, say, an auto_ptr whose scope lasts the duration of the Objective C class' lifetime.
|
Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects).
Then you get default-like C++ scoping, however I haven't used it much and I've had problems with heavily template code (Boost).
Also I don't think anyone officially supports this besides some good souls working on GCC. So I'd recommend that you unit test anything like this, and keep note that anything could go wrong.
Nevertheless being able to use C++ in objective-C, for me as a C++ person, is a relief and the risks are worth the benefits :)
|
283,646
| 283,693
|
STL Migration issues (VS 2003 -> 2005)
|
I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:
void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );
The Visual Studio error is as follows:
c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
with
[
_Ty=CObject *,
_Alloc=std::allocator<CObject *>
]
No constructor could take the source type, or constructor overload resolution was ambiguous
I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?
|
Your program is incorrect as NULL cannot be converted as an iterator. I don't really know what you want these iterators to be initialized as. If you need an iterator guarantied not to be in a container but to be still "valid", you can use a default-constructor:
typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
myvector_t::iterator itBegin = myvector_t::iterator(),
myvector_t::iterator itEnd = myvector_t::iterator() );
Note, however, that if you do so, it, itBegin and itEnd won't be comparable in a meaningful way! Only iterators obtained from a given container are comparable meaningfully. In the end, I would recommend against using defaults values for itBegin and itEnd. If you really need to not have these, create another function without the arguments and do something meaningful. i.e.:
typedef std::vector<CSomeObject*> myvector_t;
void SomeFn( myvector_t::iterator it,
myvector_t::iterator itBegin,
myvector_t::iterator itEnd );
void SomeFn( myvector_t::iterator it ); // No begin/end arguments
Another problem of your program is the use of a vector to store pointers. This is really unsafe. Make sure you never erase elements from the vector without deleting the element first. You might also have problems with algorithms copying objects around. It is better to use smart pointers in vectors.
|
283,726
| 283,970
|
Memory leak detection under Windows for GNU C/C++
|
What memory leak detection tools are available for use with open source C/C++ on Windows?
|
The mem (revised) package is an effective and straightforward tool to detect memory buffer overflows, underflows, leaks, double-deletion, and dangling references.
Original link to c.snippets.org, now invalid.
|
284,556
| 284,663
|
delete or virtual delete?
|
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do
Obj *obj = libname_newDevice();
Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I shouldn't be doing the delete?
I have obj->create(theType); which returns a class with the Obj interface.
My real question is do I need a libname_deleteDevice(); or is obj->deleteMe() fine since I have a deleteMe in the interface?
|
I would take one step further.
If you are using a factory function to create, it may be logical to use a factory function to destroy. In addition to this to make it all nice and exetion safe wrap in in an object.
class ObjWrap
{
public:
ObjWrap()
:obj(libname_newDevice())
{}
~ObjWrap()
{ libname_deleteDevice(obj);}
private:
ObjWrap(ObjWrap const&); // Dont copy
void operator=(ObjWrap const&); // Dont copy
Obj* obj;
}; // If you want to copy then you need to extra work on ref counting
// This may need some form of smart pointer.
|
284,566
| 284,720
|
How can you initialize a class with a reference member from a private constructor?
|
I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?
struct InterfaceWrapper {
InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
int someElement(void) const { return m_internal.someElement; };
private:
InterfaceWrapper(){} // initialize m_internal
SomeHugeStructure& m_internal;
};
|
As others have mentioned, if your purpose is to prevent others from calling the default constructor, then you don't want to provide a body at all, and declaring it is unnecessary since you have another constructor and the compiler won't generate it for you.
If the purpose is to limit access to friends of the class, then you would probably be best having a pointer (prefereably a smart pointer) member, and setting it to NULL.
--
Also, I'm not sure why you made this a struct rather than a class. In general making something a struct makes sense when you're exposing data members as public, similar to C. In this case, it looks like you have a conventional class, in which case the C++ convention would be to make it a class.
|
284,716
| 284,734
|
MSXML Select Nodes Not Working
|
I am working on an automated testing app, and am currently in the process of writing a function that compares values between two XML files that should be identical, but may not be. Here is a sample of the XML I'm trying to process:
<?xml version="1.0" encoding="utf-8"?>
<report xmlns="http://www.**.com/**">
<subreport name="RBDReport">
<record rowNumber="1">
<field name="Time">
<value>0</value>
</field>
<field name="Reliability">
<value>1.000000</value>
</field>
<field name="Unreliability">
<value>0.000000</value>
</field>
<field name="Availability">
<value> </value>
</field>
<field name="Unavailability">
<value> </value>
</field>
<field name="Failure Rate">
<value>N/A</value>
</field>
<field name="Number of Failures">
<value> </value>
</field>
<field name="Total Downtime">
<value> </value>
</field>
</record>
(Note there may be multiple <subreport> elements and within those, multiple <record> elements.)
What I'd like is to extract the <value> tags of two documents and then compare their values. That part I know how to do. The problem is the extraction itself.
Since I'm stuck in C++, I'm using MSXML, and have written a wrapper to allow my app to abstract away the actual XML manipulation, in case I ever decide to change my data format.
That wrapper, CSimpleXMLParser, loads an XML document and sets its "top record" to the document element of the XML document. (CRecord being an abstract class with CXMLRecord one of its subclasses, and which gives access to child records singularly or by group, and also allowing access to the "value" of the Record (values for child elements or attributes, in the case of CXMLRecord.) A CXMLRecord contains an MSXML::MSXMLDOMNodePtr and a pointer to an instance of a CSimpleXMLParser.) The wrapper also contains utility functions for returning children, which the CXMLRecord uses to return its child records.
In my code, I do the following (trying to return all <subreport> nodes just to see if it works):
CSimpleXMLParser parserReportData;
parserReportData.OpenXMLDocument(strPathToXML);
bool bGetChildrenSuccess = parserReportData.GetFirstRecord()->GetChildRecords(listpChildren, _T("subreport"));
This is always returning false. The meat of the implementation of CXMLRecord::GetChildRecords() is basically
MSXML2::IXMLDOMNodeListPtr pListChildren = m_pParser->SelectNodes(strPath, m_pXMLNode);
if (pListChildren->Getlength() == 0)
{
return false;
}
for (long l = 0; l < pListChildren->Getlength(); ++l)
{
listRecords.push_back(new CXMLRecord(pListChildren->Getitem(l), m_pParser));
}
return true;
And CSimpleXMLParser::SelectNodes() is:
MSXML2::IXMLDOMNodeListPtr CSimpleXMLParser::SelectNodes(LPCTSTR strXPathFilter, MSXML2::IXMLDOMNodePtr pXMLNode)
{
return pXMLNode->selectNodes(_bstr_t(strXPathFilter));
}
When run, the top record is definitely being set to the <report> element properly. I can do all sorts of things with it, like getting its child nodes (through the MSXML interface, not through my wrapper) or its name, etc. I know that my wrapper can work, because I use it elsewhere in the app for parsing an XML configuration file, and that works flawlessly.
I thought maybe I was doing something faulty with the XPath query expression, but every permutation I could think of gives no joy. The MSXML::IXMLDOMNodeListPtr returned by IXMLDOMNodePtr::SelectNodes() is always of length 0 when I try to deal with this XML file.
This is driving me crazy.
|
I'm used to doing this with .NET's XmlDocument objects, but I think the effect is the same here:
If the XML document includes a namespace -- even an unnamed one -- then the Xpath query has to use one as well. So, you'll have to add the namespace to the XMLDoument which you might as well give a name in the code, and the include the prefix in the XPATH query (it doesn't matter that the prefixes are different between the xml document and the xpath, as long as the namespaces sort it out)
SO, while you are using an XPath like /report/subreport/record/field/value, you actually need to first set the namespace of your document:
pXMLDoc->setProperty(_bstr_t("SelectionNamespaces"),
_bstr_t("xmlns:r="http://www.**.com/**"));
and then selectNodes() using /r:report/r:subreport/r:record/r:field/r:value
|
284,833
| 284,859
|
How do you declare arrays in a c++ header?
|
This is related to some other questions, such as: this, and some of my other questions.
In this question, and others, we see we can declare and initialise string arrays in one nice step, for example:
const char* const list[] = {"zip", "zam", "bam"}; //from other question
This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.
What I want to do is to have an array like this as as member of a class I am using, something like this:
class DataProvider : public SomethingElse
{
const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
public:
DataProvider();
~DataProvider();
char* GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?
|
Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
class DataProvider : public SomethingElse
{
static const char* const mStringData[];
public:
DataProvider();
~DataProvider();
const char* const GetData()
{
int index = GetCurrentIndex(); //work out the index based on some other data
return mStringData[index]; //error checking and what have you omitted
}
};
In the .cpp file:
const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};
|
285,200
| 285,631
|
Can Boost Spirit be used to parse byte stream data?
|
Can Spirit (part of Boost C++ library) be used to parse out binary data coming from a stream? For example, can it be used to parse data coming from a socket into structures, bytes, and individual bit flags? Thanks!
|
Boost Spirit allows for a parser to be defined using Extended Backus–Naur Form (EBNF) syntax with template meta-programming. It is very flexible and uses abstract classes in all phases of the parsing process that can be customized. In order to process a binary data stream, you would need to implement custom scanner classes since the default types are tailored for text input. You can read further in The Scanner and Parsing section of the Spirit User's Guide.
In my humble opinion, binary data streams are best handled with hand rolled serialization code. Spirit is geared more towards well formed grammars like mark-up or scripting languages. For example, The Complete Syntax of Lua is provided in EBNF. So, it might make sense to use Spirit to build a custom parser. On the other hand, a proprietary serial data link with synchronization bytes and CRC bracketing messages would require a lot more work just to define the EBNF if a context-free grammar even exists for it.
Addendum
The latest version of Boost Spirit includes functionality for dealing with binary data.
|
285,367
| 323,349
|
How do I create a filter for Microsoft Excel?
|
I want to add a file type extension to the Open Dialog of Excel (2003, 2007 if possible, 2007 only, if necessary).
When the user opens my type of file (i.e. myfile.myx), I want my application to read the file and paste the file into Excel in my own defined manner (by using Interop)
|
I think you are out of luck here. There is no documented way of extending Excel with custom import filter (as far as I know). Such a converter interface only exists for Word (http://support.microsoft.com/kb/111716).
If you want to modify the file open dialog you could try to subclass the dialog. This works for the Windows Common Dialogs (see http://www.codeproject.com/KB/dialog/customize_dialog.aspx for an example), but I suppose the Office dialogs use different messages and may not allow what you want to do.
|
285,372
| 285,380
|
automatic class templates?
|
Is there a way to have the compile deduce the template parameter automatically?
template<class T>
struct TestA
{
TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
TestB (5);
}
Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"
|
No, there isn't. Class templates are never deduced. The usual pattern is to have a make_ free function:
template<class T> TestA<T> make_TestA(T v)
{
return TestA<T>(v);
}
See std::pair and std::make_pair, for example.
In C++0x you will be able to do
auto someVariable = make_TestA(5);
to avoid having to specify the type for local variables.
|
285,482
| 296,140
|
Using PrintDlg on Vista x64 does not work, works fine on 32 bit and XP
|
We've got an app with some legacy printer "setup" code that we are still using PrintDlg for. We use a custom template to allow the user to select which printer to use for various types of printing tasks (such as reports or drawings) along with orientation and paper size/source.
It works on XP and 32-bit Vista, but on Vista x64 it gets a CDERR_MEMLOCKFAILURE via CommDlgExtendedError(). I've tried running it with just the bare-bones input in the PRINTDLG structure, but if the parameters include PD_PRINTSETUP or PD_RETURNDEFAULT, I get that error.
Since the printer selection / page setup has been split into PageSetupDlg and PrintDlgEx, there is no apparent easy transition without changing a fair amount of code and/or changing completely how we present printing and printer setup to the user.
Has anyone seen this problem on 64-bit Vista, and have you found any work-arounds?
Notes:
Application runs as Administrator due to other constraints
|
I found a related post on the Microsoft forums: On Vista x64, DocumentProperties fails from UAC-elevated process
I've verified with a sample program that PrintDlg running as non-admin works.
|
285,551
| 285,574
|
How to add a simple API to my C++ application for access by LabView?
|
I have a data acquisition program written in C++ (Visual Studio 6.0). Some clients would like to control the software from their own custom software or LabView. I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started. This is going to be VERY basic, maybe 4 or 5 commands. My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.
|
You are on the right track with a DLL. The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use. Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL.
As far as the API is concerned, you can keep it simple just like you were wanting. Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.
|
285,710
| 285,926
|
What techniques can you use to profile your code
|
Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.
The target language is C++.
I am interested in what you have personally used.
|
I've found the following quite useful:
#ifdef PROFILING
# define PROFILE_CALL(x) do{ \
const DWORD t1 = timeGetTime(); \
x; \
const DWORD t2 = timeGetTime(); \
std::cout << "Call to '" << #x << "' took " << (t2 - t1) << " ms.\n"; \
}while(false)
#else
# define PROFILE_CALL(x) x
#endif
Which can be used in the calling function as such:
PROFILE_CALL(renderSlow(world));
int r = 0;
PROFILE_CALL(r = readPacketSize());
|
285,886
| 285,894
|
In C++ You Can Have a Pointer to a Function, Can you also have a pointer to a class?
|
I'm not talking about a pointer to an instance, I want a pointer to a class itself.
|
In C++, classes are not "first class objects". The closest you can get is a pointer to its type_info instance.
|
286,105
| 286,617
|
How to synchronize C & C++ libraries with minimal performance penalty?
|
I have a C library with numerous math routines for dealing with vectors, matrices, quaternions and so on. It needs to remain in C because I often use it for embedded work and as a Lua extension. In addition, I have C++ class wrappers to allow for more convenient object management and operator overloading for math operations using the C API. The wrapper only consists of a header file and as much use on inlining is made as possible.
Is there an appreciable penalty for wrapping the C code versus porting and inlining the implementation directly into the C++ class? This library is used in time critical applications. So, does the boost from eliminating indirection compensate for the maintenance headache of two ports?
Example of C interface:
typedef float VECTOR3[3];
void v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs);
Example of C++ wrapper:
class Vector3
{
private:
VECTOR3 v_;
public:
// copy constructors, etc...
Vector3& operator+=(const Vector3& rhs)
{
v3_add(&this->v_, this->v_, const_cast<VECTOR3> (rhs.v_));
return *this;
}
Vector3 operator+(const Vector3& rhs) const
{
Vector3 tmp(*this);
tmp += rhs;
return tmp;
}
// more methods...
};
|
Your wrapper itself will be inlined, however, your method calls to the C library typically will not. (This would require link-time-optimizations which are technically possible, but to AFAIK rudimentary at best in todays tools)
Generally, a function call as such is not very expensive. The cycle cost has decreased considerably over the last years, and it can be predicted easily, so the the call penalty as such is negligible.
However, inlining opens the door to more optimizations: if you have v = a + b + c, your wrapper class forces the generation of stack variables, whereas for inlined calls, the majority of the data can be kept in the FPU stack. Also, inlined code allows simplifying instructions, considering constant values, and more.
So while the measure before you invest rule holds true, I would expect some room for improvements here.
A typical solution is to bring the C implementaiton into a format that it can be used either as inline functions or as "C" body:
// V3impl.inl
void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs)
{
// here you maintain the actual implementations
// ...
}
// C header
#define V3DECL
void V3DECL v3_add(VECTOR3 *out, VECTOR3 lhs, VECTOR3 rhs);
// C body
#include "V3impl.inl"
// CPP Header
#define V3DECL inline
namespace v3core {
#include "V3impl.inl"
} // namespace
class Vector3D { ... }
This likely makes sense only for selected methods with comparedly simple bodies. I'd move the methods to a separate namespace for the C++ implementation, as you will usually not need them directly.
(Note that the inline is just a compiler hint, it doesn't force the method to be inlined.
But that's good: if the code size of an inner loop exceeds the instruction cache, inlining easily hurts performance)
Whether the pass/return-by-reference can be resolved depends on the strength of your compiler, I've seen many where
foo(X * out)
forces stack variables, whereas
X foo()
does keep values in registers.
|
286,402
| 286,667
|
Initializing struct, using an array
|
I have a couple of array's:
const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"};
const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"};
which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of:
struct predict_cache_key {
pck() :
av_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fc(0),
gnd(0),
ag(0),
pc(0),
prl_id(0)
{ }
int av_id;
int sz_id;
int cr_id;
int cp_id;
int cv_id;
int ct_id;
int fc;
char gnd;
int ag;
int pc;
long prl_id;
};
The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct.
Any help in using C or C++ to solve the above?
|
This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g.
const string a_strs[] = {"cr=1", "ag=2", "gnd=U", NULL};
Then I would write a (private) helper function that parse the string:
bool
parse_string(const string &str, char *buffer, size_t b_size, int *num)
{
char *ptr;
strncpy(buffer, str.c_str(), b_size);
buffer[b_size - 1] = 0;
/* find the '=' */
ptr = strchr(buffer, '=');
if (!ptr) return false;
*ptr = '\0';
ptr++;
*num = atoi(ptr);
return true;
}
then you can do what qrdl has suggested.
in a simple for loop:
for (const string *cur_str = array; *cur_str; cur_str++)
{
char key[128];
int value = 0;
if (!parse_string(*cur_string, key, sizeof(key), &value)
continue;
/* and here what qrdl suggested */
if (!strcmp(key, "cr")) cr_id = value;
else if ...
}
EDIT: you should probably use long instead of int and atol instead of atoi, because your prl_id is of the type long. Second if there could be wrong formated numbers after the '=', you should use strtol, which can catch errors.
|
286,534
| 286,555
|
Enumerating all available drive letters in Windows
|
I want to enumerate all available drive letters (which aren't already taken) in Windows using VC++.
How can I do this?
|
::GetLogicalDrives() returns a list of available (read: used) drives as bits in a mask. This should include mapped network drives. Thus, you can simply walk the bits to find bits that are zero, meaning no drive is present. If in doubt, you can always call ::GetDriveType() with the drive letter + ":\" (":\\" in C code, or _T(":\\") in Unicode-aware terminology, of course), and that should return DRIVE_UNKNOWN or DRIVE_NO_ROOT_DIR if the drive is available.
|
286,606
| 288,447
|
Changing Keyboard Layout on Windows Mobile
|
In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.
Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?
Thanks!
|
You don't need to.
Just like full windows, you can set the edit control to be numeric input only. You can either do it manually or in the dialog editor in the properites for the edit control.
The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus.
|
286,677
| 286,895
|
What code changes are required to migrate C++ from VS2003 to VS2005?
|
We are considering moving the win32 build of our cross-platform C++ application from MS Visual Studio 2003 to MS Visual Studio 2005. (Yes, very forward-looking of us ;)
Should we expect to many code changes to get it compiling and working?
|
I've just migrated a comparatively large codebase from VS2003 to VS2008 via VS2005 and the majority of issues I found were const/non-const issues like assigning the return value of a function that returns a const char * to char *. Both VS2005 and VS2008 are a lot more picky when it comes to const correctness and if your existing codebase is a bit sloppy, sorry, old school when it comes to const correctness, you'll see plenty of this.
A very welcome change was that the template support in VS2005 is noticeably better than it is in VS2003 (itself a big improvement on earlier versions), which enabled me to throw out several workarounds for template related issues that the team had been dragging around since the heady days of VC++ 4.x.
One issue that you are likely to encounter are tons of warnings about "deprecated" or "insecure" functions, especially if you are using the C string functions. A lot of these are "deprecated by Microsoft" (only that they left out the "by Microsoft" part) and are still perfectly usable, but are known potential sources for buffer overflows. In the projects I converted, I set the preprocessor define _CRT_SECURE_NO_WARNINGS and disabled the warning C4996 to turn off these somewhat annoying messages.
Another issue that we came across is that MS has changed the default size of time_t either in VS2005 or in VS2008 (I apologise but I can't remember - it's definitely in VS2008 but it may already be in VS2005) so if you have to link with legacy libraries that use time_t in the interface, you'll have to use _USE_32BIT_TIME_T to revert to the older compiler's behaviour.
If your solution contains several projects, you may find that the parallel build feature (which is turned on by default) will highlight missing build dependencies. so projects are suddenly built in the wrong order but magically build correctly if you revert from parallel build back to linear build.
Overall I do prefer VS2005/8 to VS2003, and I would recommend to upgrade to VS2008 if that is an option, as the compiler is "better" than VS2005 - MS seems to have made a massive effort in improving the native C++ compiler. Part of that was already noticeable in 2005 so you'll get at least some of the benefit even if you stick to 2005.
|
286,714
| 286,752
|
What are the advantages of VS2008 over VS2005 for C++ development?
|
We are considering switching from MS Visual Studio 2003 to MS Visual Studio 2005 for our C++ development. I think jumping to 2008 might be better.
In what ways are VS2008 better than VS2005 for C++ development?
Are there any disadvantages of VS2008 over VS2005?
|
There are very little difference between 2005 and 2008 from native C++ developer point of view. However, if coming from 2003, it makes sense to upgrade directly to 2008 - the conversion process should be almost the same, and you will end up with a slightly better platform. Some new features which are available for 2008 only:
/MP option for multicore compilation (a huge timesaver if you have a mutlicore computer)
some improved debugging options for multithreaded applications
There are also some additional downloadable feature packs for 2008 only:
TR1 libraries
new MFC
|
287,053
| 287,435
|
How to determine video dimensions of an mpeg-2 program stream file
|
How do I programmatically find out the width and height of the video in an mpeg-2 transport program stream file?
Edit: I am using C++, but am happy for examples in any language.
Edit: Corrected question - it was probably program streams I was asking about
|
Check out the source code to libmpeg2, a F/OSS MPEG2 decoder. It appears that the width and height are set in the mpeg2_header_sequence() function in header.c. I'm not sure how control flows to that particular function, though. I'd suggest opening up an MPEG2 file in something using libmpeg2 (such as MPlayer) and attaching a debugger to see more closely exactly what it's doing.
|
287,259
| 287,265
|
minimum c++ make file for linux
|
I've looking to find a simple recommended "minimal" c++ makefile for linux which will use g++ to compile and link a single file and h file. Ideally the make file will not even have the physical file names in it and only have a .cpp to .o transform. What is the best way to generate such a makefile without diving into the horrors of autoconf?
The current dir contains, for example
t.cpp
t.h
and I want a makefile for that to be created. I tried autoconf but its assuming .h is gcc instead of g++. Yes, while not a beginner, I am relearning from years ago best approaches to project manipulation and hence am looking for automated ways to create and maintain makefiles for small projects.
|
If it is a single file, you can type
make t
And it will invoke
g++ t.cpp -o t
This doesn't even require a Makefile in the directory, although it will get confused if you have a t.cpp and a t.c and a t.java, etc etc.
Also a real Makefile:
SOURCES := t.cpp
# Objs are all the sources, with .cpp replaced by .o
OBJS := $(SOURCES:.cpp=.o)
all: t
# Compile the binary 't' by calling the compiler with cflags, lflags, and any libs (if defined) and the list of objects.
t: $(OBJS)
$(CC) $(CFLAGS) -o t $(OBJS) $(LFLAGS) $(LIBS)
# Get a .o from a .cpp by calling compiler with cflags and includes (if defined)
.cpp.o:
$(CC) $(CFLAGS) $(INCLUDES) -c $<
|
287,379
| 287,521
|
Parsing C++ preprocessor #if statements
|
I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.
I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc).
Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).
The only implementation I know of is GCC, and that's much too complex for this task.
|
As KeithB said, you could just let the preprocessor do this for you.
But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper #define directives in a header that's globally included.
your clients don't need to worry about -D options
you don't have to have some custom step in your build process
the code you give your clients isn't potentially semi-obfuscated
you don't introduce bugs because the tool does things subtly different from the C preprocessor
you don't have to maintain some custom tool
|
287,702
| 287,723
|
Executable reading itself
|
I need to read data added to the end of an executable from within that executable .
On win32 I have a problem that I cannot open the .exe for reading. I have tried CreateFile and std::ifstream.
Is there a way of specifying non-exclusive read access to a file that wasn't initially opened with sharing.
EDIT- Great thing about stackoverflow, you ask the wrong question and get the right answer.
|
Why not just use resources which are designed for this functionality. It won't be at the end, but it will be in the executable.
If you are adding to the .exe after it is built -- you don't have to add to the end, you can update resources on a built .exe
http://msdn.microsoft.com/en-us/library/ms648049(VS.85).aspx
|
288,034
| 288,050
|
randomness algorithm
|
I need some help regarding algorithm for randomness. So Problem is.
There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736.
How can I do this with random generation algorithm?
I can get random number
int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
then event happens
else
no event
But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.
Any suggestions?
sorry I forget to mention
I calculated chance as
double chance = (static_cast )(r) / (static_cast)(RAND_MAX);
It removed double from static_cast
double chance = (double)r/(double)(RAND_MAX);
|
Create a list of 50 numbers.
Fill them with a random number between 1 and 8 * 60 * 60.
Sort them
And you have the 50 seconds.
Note that you can have duplicates.
|
288,038
| 288,071
|
How to safely escape a string from C++
|
I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes.
Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.
Is there a function available in the CRT or somewhere in the linux headers to safely escape a string to pass to the command line ?
|
There isn't a single solution that works everywhere because different shells have different ideas of what special characters are and how they are interpreted. For bash, you could probably get away with surrounding the entire filename in single quotes after replacing every single quote in the file name with '"'"' (the first single quote stops the sequence, the "'" appends the literal single quote to the string, the final single quote starts the quoted sequence again). A better solution would be to find a way to call the program without using system, such as by using fork with one of the exec functions so there is no shell interpolation.
|
288,102
| 288,241
|
calculate seconds-to-date for pre-epoch date/times using MS VS2003
|
I have this routine that calculates the seconds-to-date for a struct tm. On Linux my implementation using mktime works fine, but
mktime on windows VS2003/.NET 1.1 returns -1 for pre-epoch datetimes.
How do I calculate meaningful time_t values (i.e.
value + secondsToEpoch == secondsToDatetime
) from a for pre-epoch dates, using ANSI C++ only (no boost, Qt either)?
Thanks for your help.
|
Looking at a couple of mktime sources on the net, they all look pretty portable so you ought to be able to grab one and just put it in your source, paying attention to legal requirements, of course.
That said, I think you have to look for the right one. What dates are you working with? If you're working with pre-1970 dates, there's a good chance you're going to need a 64-bit time_t.
There are also some weird calendar changes very early on that might be a concern, e.g., the switch to the Gregorian calendar.
|
288,178
| 288,311
|
Lambda expression exercise
|
I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...
is there a way to simplify a c++ integration function like this:
// Integral Function
double integrate(double a, double b, double (*f)(double))
{
double sum = 0.0;
// Evaluate integral{a,b} f(x) dx
for(int n = 0 ; n <= 100; ++n)
{
double x = a + n*(b-a)/100.0;
sum += (*f)(x) * (b-a)/101.0;
}
return sum;
}
by using c# and lambda expressions?
|
What about this:
public double Integrate(double a,double b, Func<double, double> f)
{
double sum = 0.0;
for (int n = 0; n <= 100; ++n)
{
double x = a + n * (b - a) / 100.0;
sum += f(x) * (b - a) / 101.0;
}
return sum;
}
Test:
Func<double, double> fun = x => Math.Pow(x,2);
double result = Integrate(0, 10, fun);
|
288,217
| 288,233
|
Forcing something to be destructed last in C++
|
I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed.
The problem I am now facing is happening when I quit the application: as order of destruction is not deterministic, it so happens that the single controllerSupervisor instance is destructed prior to (some) of the controllers themselves, and when they call the unregister method in their destructor, they do so upon an already destructed object.
The only idea I came up with so far (having a big cold, so this may not mean much) is not having the controllerSupervisor as a global variable on the stack, but rather on the heap (i.e. using new). However in that case I do not have a place to delete it (this is all in a 3rd party kind of library).
Any hints/suggestions on what possible options are would be appreciated.
|
You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction.
Take a look at http://en.wikipedia.org/wiki/Observer_pattern
|
288,282
| 292,962
|
How does VC++ mangle local static variable names?
|
Here's some code I have:
MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.
My question then is how to refer to this instance variable from a global scope. I've tried referring to it as MyClass::getInstance::instance but that doesn't work. I'm guessing getInstance has to be decorated somehow. Anyone know how?
This is in Visual Studio 2008.
|
Well, the function-scoped static instance variable doesn't show up in a .map file generated by cl.exe /Fm, and it doesn't show up when I use x programname!*MyClass* in WinDbg, so the mangled name doesn't seem to contain MyClass at all.
Option 1: Disassemble MyClass::getInstance
This approach seems easier:
0:000> uf programname!MyClass::getInstance
programname!MyClass::getInstance [programname.cpp @ 14]:
14 00401050 55 push ebp
14 00401051 8bec mov ebp,esp
15 00401053 a160b34200 mov eax,dword ptr [programname!$S1 (0042b360)]
15 00401058 83e001 and eax,1
15 0040105b 7526 jne funcstat!MyClass::getInstance+0x33 (00401083)
programname!MyClass::getInstance+0xd [programname.cpp @ 15]:
15 0040105d 8b0d60b34200 mov ecx,dword ptr [programname!$S1 (0042b360)]
15 00401063 83c901 or ecx,1
15 00401066 890d60b34200 mov dword ptr [programname!$S1 (0042b360)],ecx
15 0040106c b9b0be4200 mov ecx,offset programname!instance (0042beb0)
15 00401071 e88fffffff call programname!ILT+0(??0MyClassQAEXZ) (00401005)
15 00401076 68e03e4200 push offset programname!`MyClass::getInstance'::`2'::`dynamic atexit destructor for 'instance'' (00423ee0)
15 0040107b e8f3010000 call programname!atexit (00401273)
15 00401080 83c404 add esp,4
programname!MyClass::getInstance+0x33 [programname.cpp @ 16]:
16 00401083 b8b0be4200 mov eax,offset programname!instance (0042beb0)
17 00401088 5d pop ebp
17 00401089 c3 ret
From this we can tell that the compiler called the object $S1. Of course, this name will depend on how many function-scoped static variables your program has.
Option 2: Search memory for the object
To expand on @gbjbaanb's suggestion, if MyClass has virtual functions, you might be able to find its location the hard way:
Make a full memory dump of the process.
Load the full memory dump into WinDbg.
Use the x command to find the address of MyClass's vtable:
0:000> x programname!MyClass::`vftable'
00425c64 programname!MyClass::`vftable' =
Use the s command to search the process's virtual address space (in this example, 0-2GB) for pointers to MyClass's vtable:
0:000> s -d 0 L?7fffffff 00425c64
004010dc 00425c64 c35de58b cccccccc cccccccc d\B...].........
0040113c 00425c64 8bfc458b ccc35de5 cccccccc d\B..E...]......
0042b360 00425c64 00000000 00000000 00000000 d\B.............
Use the dt command to find the class's vtable offset, and subtract that from the addresses returned from the search. These are possible addresses for the object.
0:000> dt programname!MyClass
+0x000 __VFN_table : Ptr32
+0x008 x : Int4B
+0x010 y : Float
Use dt programname!MyClass 0042b360 to examine the object's member variables, testing the hypothesis that the object is located at 0042b360 (or some other address). You will probably get some false positives, as I did above, but by inspecting the member variables you may be able to figure out which one is your singleton.
This is a general technique for finding C++ objects, and is kind of overkill when you could just disassemble MyClass::getInstance.
|
288,465
| 289,207
|
How can I access element attributes from an IXMLDOMNode?
|
I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?
Part of me wants to downcast the Node to an Element, but I couldn't get the cast to work.
I tried
MSXML2::IXMLDOMElementPtr pParentElement;
pParentNode->QueryInterface(__uuidof(MSXML2::IXMLDOMElement),
(void**) &pParentElement);
Which results in the following runtime error:
0x0057cc58 _com_error::`scalar deleting destructor'(unsigned int)
The other route I tried was to just use nodes:
MSXML2::IXMLDOMNodePtr pParentNode =
pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMNamedNodeMap* pParentAttributes;
pParentNode->get_attributes(&pParentAttributes);
MSXML2::IXMLDOMNodePtr pCategoryNameNode =
pParentAttributes->getNamedItem("Category");
VARIANT value;
pCategoryNameNode->get_nodeValue(&value);
CString categoryName = value;
This fails at "parentNode->get_attributes()".
It seems like I'm missing something; the API should not be this hard to use.
--edit--
What I was missing was that the selectSingleNode call was failing, leaving me with a NULL pointer. You can't call QueryInterface on that, neither can you call get_attributes on it :P
I've selected the answer that fits the question that I asked, not the answer that helped me to realise that I asked the wrong question.
|
I don't see anything wrong with what you have written.
The smart com pointers will help you convert if they can, you don't have to write the query interface yourself.
MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMElementPtr pParentElement( pParentNode );
Using the Ptr types is a bit painfull in my opinion, though the MSXML interface favours them.
Here is an equivelant example using ATL
CComPtr<IXMLDOMNode> node = ...;
CComQIPtr<IXMLDOMElement> elementNode( node );
if( elementNode ) {
// it was an element!
} else {
// it's something else try again?
}
The other attempt would look like...
CComPtr<IXMLDOMNamedNodeMap> attributes;
node->get_attributes( &attributes );
if( attributes ) {
_bstr_t name( L"category" );
attributes->getNamedItem(name);
}
And it's COM, it's always hard to use in C++ :(
|
288,739
| 20,136,256
|
Generate random numbers uniformly over an entire range
|
I need to generate random numbers within a specified interval, [max;min].
Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.
Currenly I am generating as:
for(int i=0; i<6; i++)
{
DWORD random = rand()%(max-min+1) + min;
}
From my tests, random numbers are generated around one point only.
Example
min = 3604607;
max = 7654607;
Random numbers generated:
3631594
3609293
3630000
3628441
3636376
3621404
From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?
|
Why rand is a bad idea
Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX), and is therefore discouraged.
C++11 and generation over a range
With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution. Here's an example:
#include <iostream>
#include <random>
int main()
{
const int range_from = 0;
const int range_to = 1000;
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<int> distr(range_from, range_to);
std::cout << distr(generator) << '\n';
}
Try it online on Godbolt
And here's the running example.
Template function may help some:
template<typename T>
T random(T range_from, T range_to) {
std::random_device rand_dev;
std::mt19937 generator(rand_dev());
std::uniform_int_distribution<T> distr(range_from, range_to);
return distr(generator);
}
Other random generators
The <random> header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.
How can I shuffle a container?
The standard provides std::shuffle, which can be used as follows:
#include <iostream>
#include <random>
#include <vector>
int main()
{
std::vector<int> vec = {4, 8, 15, 16, 23, 42};
std::random_device random_dev;
std::mt19937 generator(random_dev());
std::shuffle(vec.begin(), vec.end(), generator);
std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';});
}
Try it online on Godbolt
The algorithm will reorder the elements randomly, with a linear complexity.
Boost.Random
Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random. Its interface is very similar to the C++11 one.
|
289,157
| 289,218
|
How can I pass a reference parameter (&) (not pointer) using p/invoke in C#?
|
I have a C++ API prototype
void Func(int& size);
How can I translate it to P/Invoke in C#?
From what I know, if I use
public static extern Func(ref int size);
, the function will receive a pointer to the int instead of the value.
|
(Ooops... meant this as an answer, not a comment).
And when you call it from C++, the function will receive a pointer also. How else do you think references are implemented? Func() will treat that pointer as a reference, so how it gets there isn't important.
|
289,381
| 289,404
|
Strange issue running infinite while loop in EXE
|
I am facing strange issue on Windows CE:
Running 3 EXEs
1)First exe doing some work every 8 minutes unless exit event is signaled.
2)Second exe doing some work every 5 minutes unless exit event signaled.
3)Third exe while loop is running and in while loop it do some work at random times.
This while loop continues until exit event signaled.
Now this exit event is global event and can be signaled by any process.
The Problem is
When I run First exe it works fine,
Run second exe it works fine,
run third exe it works fine
When I run all exes then only third exe runs and no instructions get executed in first and second.
As soon as third exe gets terminated first and second starts get processing.
It that can be the case that while loop in third exe is taking all CPU cycles?
I havn't tried putting Sleep but I think that can do some tricks.
But OS should give CPU to all processes ...
Any thoughts ???
|
Put the while loop in the third EXE to Sleep each time through the loop and see what happens. Even if it doesn't fix this particular probem, it isn't ever good practice to poll with a while loop, and even using Sleep inside a loop is a poor substitute for a proper timer.
|
289,389
| 289,391
|
What happens to namespace?
|
when a dll is created out of the source code in a given namespaces a,b with functions a::open,b::open will there be any conflict in calling these function.
|
No, because the function names exported from the DLLs are the C++ mangled names. The mangled names include the namespace, so there will be no conflict.
|
289,397
| 289,407
|
How are DLLs created out of C++ source, and how are they used in other sources?
|
How are DLLs created out of C++ source code, and how are they used in other sources?
|
The DLL is a 'Dynamic Link Library' which works a lot like other libraries but is not linked with your executable application. At run time you can call specific functions for loading your DLL and executing its exported methods.
You can try creating a DLL yourself- create a project using visual studio and specify a DLL. This will create some of the base constructs for your project such as settings for your project to compile the DLL and also some base code for exposing methods, objects, or variables.
There are many walk through's to help you at this point: check here.
So, to summarize:
A DLL is a library which you can be loaded at runtime. This is a very flexible 'plug-in' model. Example: You can programmatically select and load different DLL at runtime. Each DLL can be a 'plug-in' to provide different functionality.
A DLL Has an entry point. Just like your Main function of your command line executable is the entry point, the DLL has an entry point function which is called when different events occur on the DLL such as loading, unloading, and more.
To use a DLL you must use the exported objects or methods of the DLL.
When Calling these exported functions from another application it is very important that you match compatible types! Also, make sure the calling conventions are compatible
|
289,559
| 289,671
|
Class layout in C++: Why are members sometimes ordered?
|
The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in. At the same time, compilers are free to choose the mutual ordering of the access sections themselves. This freedom makes it impossible in theory to link binaries created by different compilers. So what are the remaining reasons for the strict in-section ordering? And does the upcoming C++09 new C++11 standard provide a way to fully determine object layouts "by hand"?
|
This freedom makes it impossible in theory to link binaries created by different compilers.
It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of operator new and delete, data type sizes...
So what are the remaining reasons for the strict in-section ordering?
C compatibility, I would have thought, so that a struct defined in C packs the same way it does in C++ for a given compiler set.
And does the new C++0911 standard provide a way to fully determine object layouts "by hand"?
No, no more than the current standard does.
For a class or struct with no vtable and entirely private (or public) fields, though, it's already possible if you use the [u]int[8|16|32|64]_t types. What use case do you have for more than this?
|
289,568
| 290,250
|
Can C++ access sections be interleaved?
|
The C++ standard imposes an ordering on class member variables in memory. It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section. Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way. For example:
class X {
public:
int i;
int j;
private:
int k;
int n;
}
Does the standard allow compilers to lay out the data members in the order i, k, j, n? This would give compilers some (limited) freedom in optimizing object layout without violating the standard.
|
I checked out the C++ standard. In section 9.2, paragraph (or clause or whatever) 12, it says "The order of allocation of nonstatic data members separated by an access-specifier is unspecified." "Unspecified" means implementation-dependent behavior that need not be documented.
Therefore, the standard is explicitly saying nothing about the allocation, except that i must precede j and k must precede n. Therefore, a compiler is allowed to allocate in the order i, k, j, n, and nothing about the ordering need be documented.
|
289,715
| 289,747
|
Last key in a std::map
|
I am looking for the highest key value (a defined by the comparison operator) of a std::map.
Is this guaranteed to be
map.rbegin()->first
?
(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map)
If not, please advise. I cannot change the data structure.
|
Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.
[Edit: as Charles Bailey points out in his answer, your code gives the greatest key if it exists - i.e. if the map is non-empty]
|
289,779
| 294,549
|
Calculating a boundary around several linked rectangles
|
I am working on a project where I need to create a boundary around a group of rectangles.
Let's use this picture as an example of what I want to accomplish.
EDIT: Couldn't get the image tag to work properly, so here is the full link:
http://www.flickr.com/photos/21093416@N04/3029621742/
We have rectangles A and C who are linked by a special link rectangle B. You could think of this as two nodes in a graph (A,C) and the edge between them (B). That means the rectangles have pointers to each other in the following manner: A->B, A<-B->C, C->B
Each rectangle has four vertices stored in an array where index 0 is bottom left, and index 3 is bottom right.
I want to "traverse" this linked structure and calculate the vertices making up the boundary (red line) around it. I already have some small ideas around how to accomplish this, but want to know if some of you more mathematically inclined have some neat tricks up your sleeves.
The reason I post this here is just that someone might have solved a similar problem before, and have some ideas I could use. I don't expect anyone to sit down and think this through long and hard. I'm going to work on a solution in parallell as I wait for answers.
Any input is greatly appreciated.
|
Using the example, where rectangles are perpendicular to each other and can therefore be presented by four values (two x coordinates and two y coordinates):
1 2 3 4 5 6
1 +---+---+
| |
2 + A +---+---+
| | B |
3 + + +---+---+
| | | | |
4 +---+---+---+---+ +
| |
5 + C +
| |
6 +---+---+
1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates
1 3 4 5 6
2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates
1 2 3 4 6
3) create a 2D array by number of gaps between the unique x coordinates * number of gaps between the unique y coordinates. It only needs to be one bit per cell, so in c++ a vector<bool> with likely give you a very memory-efficient version of this
4 * 4
4) paint all the rectangles into this grid
1 3 4 5 6
1 +---+
| 1 | 0 0 0
2 +---+---+---+
| 1 | 1 | 1 | 0
3 +---+---+---+---+
| 1 | 1 | 1 | 1 |
4 +---+---+---+---+
0 0 | 1 | 1 |
6 +---+---+
5) for each cell in the grid, for each edge, if the cell beside it in that cardinal direction is not painted, draw the boundary line for that edge
In the question, the rectangles are described as being four vectors where each represents a corner. If each rectangle can be at arbitrary and different rotation from others, then the approach I've outlined above won't work. The problem of finding the path around a complex polygon is regularly solved by vector graphics rasterizers, and a good approach to solving the problem is using a library such as Cairo to do the work for you!
|
289,838
| 289,903
|
Posting to a URL with wxWidgets
|
Does anyone have some sample code showing how to POST to a URL using wxWidgets? The documentation and discussion forums imply that it's possible but the methods in wxHTTP are very low-level compared to what you find in .NET and scripting languages like Perl and Ruby. Do I actually have to create the HTTP request myself and send it to the server via the SocketOutputStream? Am I missing something?
|
I came across a similar problem initially and ended up using Curl instead as it's also cross platform and is very easy to use.
Tim
|
290,034
| 293,219
|
Is there a way to use pre-compiled headers in VC++ without requiring stdafx.h?
|
I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests.
My first instinct is to remove all these stdafx.h files which, for the most part, contain #include directives and place those #includes directly in the source files as needed.
This would make it necessary to turn off pre-compiled headers since they are dependent on having a file like stdafx.h to determine where the pre-compiled headers stop.
Is there a way to keep pre-compiled headers without the stdafx.h dependencies? Is there a better way to approach this problem?
|
Yes, there is a better way.
The problem, IMHO, with the 'wizard style' of precompiled headers is that they encourage unrequired coupling and make reusing code harder than it should be. Also, code that's been written with the 'just stick everything in stdafx.h' style is prone to be a pain to maintain as changing anything in any header file is likely to cause the whole codebase to recompile every time. This can make simple refactoring take forever as each change and recompile cycle takes far longer than it should.
A better way, again IMHO, is to use #pragma hdrstop and /Yc and /Yu. This enables you to easily set up build configurations that DO use precompiled headers and also build configurations that do not use precompiled headers. The files that use precompiled headers don't have a direct dependency on the precompiled header itself in the source file which enables them to be build with or without the precompiled header. The project file determines what source file builds the precompiled header and the #pragma hdrstop line in each source file determines which includes are taken from the precompiled header (if used) and which are taken directly from the source file... This means that when doing maintenance you would use the configuration that doesn't use precompiled headers and only the code that you need to rebuild after a header file change will rebuild. When doing full builds you can use the precompiled header configurations to speed up the compilation process. Another good thing about having the non-precompiled header build option is that it makes sure that your cpp files only include what they need and include everything that they need (something that is hard if you use the 'wizard style' of precompiled header.
I've written a bit about how this works here: http://www.lenholgate.com/blog/2004/07/fi-stlport-precompiled-headers-warning-level-4-and-pragma-hdrstop.html (ignore the stuff about /FI) and I have some example projects that build with the #pragma hdrstop and /Yc /Yu method here: http://www.lenholgate.com/blog/2008/04/practical-testing-16---fixing-a-timeout-bug.html .
Of course, getting from the 'wizard style' precompiled header usage to a more controlled style is often non-trivial...
|
290,038
| 290,048
|
Is the return type part of the function signature?
|
In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
|
Normal functions do not include the return type in their signature.
(note: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details).
Introduction
However, the matter about functions and function declarations in the Standard is complicated. There are two layers that have to be considered:
Declarations
Entities
The so-called function declaration may declare a function entity or a template entity. If a function entity is declared, then you either have to do with an explicit specialization of a function template (with all arguments specified), or a declaration of an ordinary function. If a template entity is declared, then you are declaring a primary function template, or an explicit specialization where some arguments are not specified. (This is very similar to the relation of "object declaration" and objects or references: The former may declare either an object or a reference. So an object declaration may not necessarily declare an object!).
The Standard defines the signature of a function to include the following at 1.3.10:
The types of its parameters and, if the function is a class member, the cv- qualifiers (if any) on the function itself and the class in which the member function is declared. The signature of a function template specialization includes the types of its template arguments. (14.5.5.1)
It's missing the return type in this definition, which is part of the signature of a function template specialization (i.e a function declaration that declares a function which is a specialization of a template), as pointed out by 14.5.5.1 (recent C++0x working papers fixed that already to mention the return type in 1.3.10 too):
The signature of a function template specialization consists of the signature of the function template and of the actual template arguments (whether explicitly specified or deduced).
The signature of a function template consists of its function signature, its return type and its template parameter list.
So what exactly does a signature contain, again?
So, when we ask about the signature of a function, we have to give two answers:
For functions that are specializations of function templates, the signature includes the return type.
For functions that are not specializations, the return type is not part of the signature.
Notice, however, that the return type, in any case, is a significant part of the type of a function. That is, the following is not valid:
void f();
int (*pf)() = &f; // different types!
When is an overload invalid if only the return type differs?
Major compilers currently reject the following code:
int f();
double f(); // invalid
But accept the following code:
template<typename T> int f();
template<typename T> double f(); // invalid?
However, the Standard does forbid a function declaration that only differs in the return type (when defining when an overload is valid, and when not). It does not define precisely what "differs only by return type" means, though.
Standard paragraph references:
When can a function declaration be overloaded: 13.1
What is a function declaration: 7/2 and 7/5
What is the signature of a function template/specialization: 14.5.5.1
For reference, here is what the most recent C++0x draft n3000 says about "signature" in 1.3.11, which is much more complete in its coverage of the different type of entities:
the name and the parameter type list (8.3.5) of a function, as well as the class or namespace of which it is a member. If a function or function template is a class member its signature additionally includes the cv-qualifiers (if any) and the ref-qualifier (if any) on the function or function template itself. The signature of a function template additionally includes its return type and its template parameter list. The signature of a function template specialization includes the signature of the template of which it is a specialization and its template arguments (whether explicitly specified or deduced). [ Note: Signatures are used as a basis for name mangling and linking. — end note ]
|
290,139
| 290,264
|
Event Handler for Minimize and Maximize Window
|
I am developing an application for PocketPC. When the application starts the custom function SetScreenOrientation(270) is called which rotates the screen. When the application closes the function SetScreenOrientation(0) is called which restores the screen orientation.
This way the screen orientation isn't restored if the user minimizes the application and this is not acceptable.
Does anyone know where (in which event handlers) should SetScreenOrientation(int angle) be called to set the screen orientation on application start, restore orientation on minimize, set the orientation on maximize and restore the orientation on close?
Actually I don't know which event handler handles the Minimize and Maximize event.
|
The correct message is WM_SIZE, but Daemin's answer points to the wrong WM_SIZE help topic. Check the wParam. Be careful as your window may be maximized but hidden.
|
290,436
| 318,750
|
Macro Replacement during Code Generation
|
Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining.
Is there a way that I can optimize it without manipulating the string?
|
You must tokenize your input before starting this kind of process. (I can't recommend the famous Dragon Book highly enough - even the ancient edition stood the test of time, the updated 2006 version looks great). Compiling is the sort of job that's best split up into smaller phases: if your first phase performs lexical analysis into tokens, splitting lines into keywords, identifiers, constants, and so on, then it's much simpler to find the references to macros and look them up in a symbol table. (It's also relatively easier to use a tool like lex or flex or one of their modern equivalents to do this job for you, than to attempt to do it from scratch).
The 'clue' seems to be if the code has more number of macros then the code generation takes so much of time. That sounds like the process is linear in the number of macros, which is certainly too much. I'm assuming this process occurs one line at a time (if your language allows that, obviously that has enormous value, since you don't need to treat the program as one huge string), and the pseudocode looks something like
for(each line in the program)
{
for(each macro definition)
{
test if the macro appears;
perform replacement if needed;
}
}
That clearly scales with the number of macro definitions.
With tokenization, it looks something like this:
for(each line in the program)
{
tokenize the line;
for(each token in the line)
{
switch(based on the token type)
{
case(an identifier)
lookup the identifier in the table of macro names;
perform replacement as necessary;
....
}
}
}
which scales mostly with the size of the program (not the number of definitions) - the symbol table lookup can of course be done with more optimal data structures than looping through them all, so that no longer becomes the significant factor. That second step is something that again programs like yacc and bison (and their more modern variants) can happily generate code to do.
afterthought: when parsing the macro definitions, you can store those as a token stream as well, and mark the identifiers that are the 'placeholder' names for parameter replacement. When expanding a macro, switch to that token stream. (Again, something things like flex can easily do).
|
290,484
| 290,516
|
Simple text menu in C++
|
I am writing a silly little app in C++ to test one of my libraries. I would like the app to display a list of commands to the user, allow the user to type a command, and then execute the action associated with that command. Sounds simple enough.
In C# I would end up writing a list/map of commands like so:
class MenuItem
{
public MenuItem(string cmd, string desc, Action action)
{
Command = cmd;
Description = desc;
Action = action;
}
public string Command { get; private set; }
public string Description { get; private set; }
public Action Action { get; private set; }
}
static void Main(string[] args)
{
var items = new List<MenuItem>();
items.Add(new MenuItem(
"add",
"Adds 1 and 2",
()=> Console.WriteLine(1+2)));
}
Any suggestions on how to achieve this in C++? I don't really want to define separate classes/functions for each command. I can use Boost, but not TR1.
|
A very common technique is to use function pointers, or boost::function, indexed by the item name, or by having a vector of them and indexing by the item index for this job. Simple example using the item name:
void exit_me(); /* exits the program */
void help(); /* displays help */
std::map< std::string, boost::function<void()> > menu;
menu["exit"] = &exit_me;
menu["help"] = &help;
std::string choice;
for(;;) {
std::cout << "Please choose: \n";
std::map<std::string, boost::function<void()> >::iterator it = menu.begin();
while(it != menu.end()) {
std::cout << (it++)->first << std::endl;
}
std::cin >> choice;
if(menu.find(choice) == menu.end()) {
/* item isn't found */
continue; /* next round */
}
menu[choice](); /* executes the function */
}
C++ doesn't have a lambda feature yet, so you really have to use functions for this task, sadly. You can use boost::lambda, but note it is just simulating lambdas, and nowhere near as powerful as a native solution:
menu["help"] = cout << constant("This is my little program, you can use it really nicely");
Note the use of constant(...), since otherwise boost::lambda wouldn't notice that this is supposed to be a lambda expression: The compiler would try to output the string using std::cout, and assign the result (an std::ostream reference) to menu["help"]. You can still use boost::function, since it will accept everything returning void and taking no arguments - including function objects, which is what boost::lambda creates.
If you really don't want separate functions or boost::lambda, you can just take print out a vector of the item names, and then switch on the item number given by the user. This is probably the easiest and most straight forward way of doing it.
|
290,488
| 290,521
|
Does this code remove a file extension?
|
This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:
char DestFile[256];
char DestFile2[256];
//This part is just to show an example
strcpy(DestFile, "/foo/boo/goo.gz")
strcpy ( DestFile2, DestFile );
Ptr = strrchr ( DestFile2, '.' );
if ( Ptr != 0 ) {
if ( ( strcmp ( Ptr, ".gz" ) == 0 ) ||
( strcmp ( Ptr, ".Z" ) == 0 ) ) {
*Ptr = 0;
rename ( DestFile, DestFile2 );
}
}
DestFile2 is not set anywhere else in the function. I compiled the code above, and printing out the DestFile shows nothing has changed. The only thing i can think of that this does is removing the file extension (*Ptr=0) but my knowledge of C is very limited...
Any ideas? It looks like every time it gets a file with .gz or .z it renames the file to the same name.
|
You are correct.
In C a string is an array of chars terminated by a character with ASCII code 0.
So, first, DestFile is copied to DestFile2
Then a scan from the right is performed, to find the right-most occurrence of '.'
This returns a pointer to the char that matches, or null if no occurrence is found.
So now you have (example name: myfile.gz)
DestFile2
|- Ptr
v
M y f i l e . g z \0
Then it compares if the string starting at Ptr matches .Z or .gz and if so, sets the value of the char that Ptr points to to \0, effectively truncating the string.
After setting Ptr to \0 you now have
M y f i l e \0 g z \0
Remember that c thinks a string is done when we reach a \0, so the last rename effectively says
rename("myfile.gz", "myfile");
|
290,632
| 290,658
|
How to overload operator<< that doesn't take or return ostream
|
Original Question
I am writting a logging class where the goal is to be able to do this:
// thread one
Logger() << "Some string" << std::ios::hex << 45;
// thread two
Logger() << L"Some wide string" << std::endl;
Currently my Logger header looks something like this:
#pragma once;
#include <ostream>
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
};
template <typename T>
Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
Some notes about this class:
Cross platform compatibility is not an issue.
Inside of Logger.cpp there is a singleton class that takes care of creating the "real" ostream.
The Logger constructor and deconstructor perform the necessary locking of the singleton.
I have three problems:
How do I make the operator<< function a friend or member so I can set out_stream as private?
How do I make the operator<< function work for manipulators?
How can I add a specialization so that if T is a WCHAR* or std::wstring that it will convert it to char* or std::string before passing it to out_stream? (I can do the conversion. Losing high unicode characters isn't a problem in my case.)
Summary of things learned in answers:
Put template BEFORE friend instead of after.
std::ios::hex is not a manipulator. std::hex is a manipulator.
End Result
#pragma once
#include <ostream>
#include <string>
std::string ConvertWstringToString(std::wstring wstr);
class Logger
{
public:
Logger();
~Logger();
template <typename T>
Logger& operator<< (T data) {
*out << data;
return *this;
}
Logger& operator<< (std::wstring data) {
return *this << ConvertWstringToString(data);
}
Logger& operator<< (const wchar_t* data) {
std::wstring str(data);
return *this << str;
}
private:
std::ostream* out;
};
|
You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator<<... syntax):
class Logger
{
public:
Logger();
~Logger();
std::ostream* out_stream;
template <typename T>
friend Logger& operator<< (Logger& logger, T thing) {
*logger.out_stream << thing;
return logger;
}
/* special treatment for std::wstring. just overload the operator! No need
* to specialize it. */
friend Logger& operator<< (Logger& logger, const std::wstring & wstr) {
/* do something here */
}
};
The alternative, to keep your code as it is and just make the operator<< template a friend, you add this line into your class definition:
template <typename T>
friend Logger& operator<< (Logger& logger, T thing);
For the manipulator problem, i will just give you my code i write some time ago:
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename Char, typename Traits = char_traits<Char> >
struct logger{
typedef std::basic_ostream<Char, Traits> ostream_type;
typedef ostream_type& (*manip_type)(ostream_type&);
logger(ostream_type& os):os(os){}
logger &operator<<(manip_type pfn) {
if(pfn == static_cast<manip_type>(std::endl)) {
time_t t = time(0);
os << " --- " << ctime(&t) << pfn;
} else
os << pfn;
return *this;
}
template<typename T>
logger &operator<<(T const& t) {
os << t;
return *this;
}
private:
ostream_type & os;
};
namespace { logger<char> clogged(cout); }
int main() { clogged << "something with log functionality" << std::endl; }
};
Note that it is std::hex , but not std::ios::hex. The latter is used as a manipulator flag for the setf function of streams. Note that for your example, tho, no special treatment of manipulators is required. The above special treatment of std::endl is only needed because i do stream the time in addition when std::endl is used.
|
290,913
| 290,921
|
C++: Derived + Base class implement a single interface?
|
In C++, is it possible to have a base plus derived class implement a single interface?
For example:
class Interface
{
public:
virtual void BaseFunction() = 0;
virtual void DerivedFunction() = 0;
};
class Base
{
public:
virtual void BaseFunction(){}
};
class Derived : public Base, public Interface
{
public:
void DerivedFunction(){}
};
void main()
{
Derived derived;
}
This fails because Derived can not be instantiated. As far as the compiler is concerned Interface::BaseFunction is never defined.
So far the only solution I've found would be to declare a pass through function in Derived
class Derived : public Base, public Interface
{
public:
void DerivedFunction(){}
void BaseFunction(){ Base::BaseFunction(); }
};
Is there any better solution?
EDIT: If it matters, here is a real world problem I had using MFC dialogs.
I have a dialog class (MyDialog lets say) that derives from CDialog. Due to dependency issues, I need to create an abstract interface (MyDialogInterface). The class that uses MyDialogInterface needs to use the methods specific to MyDialog, but also needs to call CDialog::SetParent. I just solved it by creating MyDialog::SetParent and having it pass through to CDialog::SetParent, but was wondering if there was a better way.
|
C++ doesn't notice the function inherited from Base already implements BaseFunction: The function has to be implemented explicitly in a class derived from Interface. Change it this way:
class Interface
{
public:
virtual void BaseFunction() = 0;
virtual void DerivedFunction() = 0;
};
class Base : public Interface
{
public:
virtual void BaseFunction(){}
};
class Derived : public Base
{
public:
virtual void DerivedFunction(){}
};
int main()
{
Derived derived;
}
If you want to be able to get away with only implementing one of them, split Interface up into two interfaces:
class DerivedInterface
{
public:
virtual void DerivedFunction() = 0;
};
class BaseInterface
{
public:
virtual void BaseFunction() = 0;
};
class Base : public BaseInterface
{
public:
virtual void BaseFunction(){}
};
class Derived : public DerivedInterface
{
public:
virtual void DerivedFunction(){}
};
class Both : public DerivedInterface, public Base {
public:
virtual void DerivedFunction(){}
};
int main()
{
Derived derived;
Base base;
Both both;
}
Note: main must return int
Note: it's good practise to keep virtual in front of member functions in the derived that were virtual in the base, even if it's not strictly required.
|
290,952
| 291,001
|
How to know (in GCC) when given macro/preprocessor symbol gets declared?
|
Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.
Is it possible? If not, are there any partial solutions that may help?
Feel free to add comments with clarification requests.
Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.
|
Use -E :
# shows preprocessed source with cpp internals removed
g++ -E -P file.cc
# shows preprocessed source kept with macros and include directives
g++ -E -dD -dI -P file.cc
The internals above are line-markers for gcc which are kinda confusing when you read the output. -P strips them
-E Stop after the preprocessing stage; do not run the compiler proper.
The output is in the form of preprocessed source code, which is sent to the
standard output.
Input files which don't require preprocessing are ignored.
Note: comments correctly complain this is only a partial solution. It won't tell you when a macro will be replaced. It shows you the preprocessed source, which can be helpful anyway.
|
291,065
| 291,261
|
Saving extra data in a dll, how did they do it?
|
let me tell you a bit about where this question came from. I have been playing around with the SDK of Serious Sam 2, a first person shooter which runs on the Serious Engine 2. This engine introduces something called MetaData. MetaData is used in the engine to serialize classes and be able to edit them in the editor environment (Serious Editor 2). So for example, instead of:
class CSomeGameItem : CEntity
{
public:
int iHealthToGive;
}
Which will not show up in the editor, you would do:
meta ver(1) class CSomeGameItem : CEntity _("Some game item")
{
public:
meta int iHealthToGive; _("Amount of health to give")
}
Now when making a level, you can insert a "Some game item" entity into your level, and edit the one property it has. Now, I know Croteam (the developers of said game and engine) are using an extra compiler (Mdc, meta data compiler) to inject extra information about classes and their variables into the dll files, to make this metadata system possible. Does anyone have any clue as to how they did this?
Oh, btw, the meta, ver() and _() keywords are #define'd to nothing in their code, so the "normal" compiler ignores them.
|
This looks somewhat similar to Qt's moc (meta object compiler). In Qt's case, it generates extra C++ source files which are then compiled and linked together with the original source files.
A possible implementation in your example would be for the generated files to implement a set of functions which can be called to get the extra information, to set the properties, and so on.
|
291,559
| 291,660
|
Using mixed DLLs from /clr:pure projects
|
I'm building a project along with a Dll.
The Dll must support native code so I declared it as a /clr.
My project was initialy also a /clr project and everything was fine. However I'd like to include some NUnit testing so I had to switch my main project from /clr to /clr:pure.
Everything still compiles but any Dll call generates a runtime error. When I revert back to /clr everything is ok
In my Dll, exported functions are declared as follow :
#define DllExport __declspec( dllexport )
DllExport bool DisplayScan(bool bShow, bool bAllPasses) { }
I also made a .def file containing the real names of all the exported functions
LIBRARY "Controller"
EXPORTS
DisplayScan
From my main project my imports are declared as follow :
#define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static
_DllImport bool DisplayScan(bool bShow, bool bAllPasses)
Anyone ever encountered such a problem?
|
Ok everything is working now
In fact, it has been working from the beginning.
Moral : don't try to cast a char* into a std::string
Weird thing : its ok in /clr until you return from the function. It crashes right away in /clr:pure
|
291,745
| 291,776
|
Interview question about debugging, multithreading
|
I had telephone interview question yesterday.
The interviewer asked me if I had faced any challenging debugging issue?
I told him I once faced a problem debugging someone else's code and it took me 3-4 days to solve that. I used Windbg, symbols and a crash dump to solve the problem.
Now is this enough to tell? What is interviewer expecting?
I don't know what else to tell, I faced that problem quite some time back and can't explain all details...
This question is very very common and I am not sure what the right answer to it?
One more question that is very common:
Have you worked on multi-threaded applications? How can you find out deadlock?
Answer: Well to find deadlock we can look at snapshot of process in memory and can look at threads that are waiting.
Then next question: What can you do to avoid deadlock?
Use waitformultipleobjects
Maintain sequence of critical sections
What do you guys say?
|
The general rule for interviews is to use the STAR model (my co-op coordinator is going to be proud here...):
S - Describe the situation you were in
T - Explain the task, providing enough info so that the interviewer understands the problem.
A - Describe the action you took to solve the problem.
R - What were the results of your actions
If you provide a concise answer, not too short or too long, 99.9% of interviewers will be satisfied.
|
291,792
| 291,949
|
win32 select all on edit ctrl (textbox)
|
I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit Select All it doesn't select all. I can right click and click Select All but CTRL + A doesn't do anything. Why?
wnd = CreateWindow("EDIT", 0,
WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
x, y, w, h,
parentWnd,
NULL, NULL, NULL);
|
I tend to use MFC (forgive me) instead of Win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control):
The edit control uses WM_CHAR for
accepting characters, not WM_KEYDOWN
etc. You must Translate() your
messages or you ironically won't be
able to edit the text in the edit
control.
I don't know if this applies to BoltBait's response, but I suspect it does.
(I found this at http://msdn.microsoft.com/en-us/library/bb775462(VS.85).aspx)
|
291,871
| 292,438
|
How to set a timeout on blocking sockets in boost asio?
|
Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?
I.e. I want to set a timeout on blocking socket in boost asio?
socket.read_some(boost::asio::buffer(pData, maxSize), error_);
Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.
|
Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via setsocktopt(). I don't know if boost::asio provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.
For a sake of completeness here's the description from the man page:
SO_RCVTIMEO and SO_SNDTIMEO
Specify the receiving or sending timeouts until reporting an
error. The argument is a struct timeval. If an input or output
function blocks for this period of time, and data has been sent
or received, the return value of that function will be the
amount of data transferred; if no data has been transferred and
the timeout has been reached then -1 is returned with errno set
to EAGAIN or EWOULDBLOCK just as if the socket was specified to
be non-blocking. If the timeout is set to zero (the default)
then the operation will never timeout. Timeouts only have
effect for system calls that perform socket I/O (e.g., read(2),
recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for
select(2), poll(2), epoll_wait(2), etc.
|
291,938
| 291,964
|
why is this legal, c++ typedef func
|
i did this in msvc 2005.
typedef void (*cleanup_t)();
void func(cleanup_t clean)
{
cleanup_t();
}
Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this code gave me problems.
What is cleanup_t(); really doing and what is the point? now for laughs i tried int() and that worked also.
|
It's executing a default initializer for the cleanup_t type to create a temporary of that type, and then never actually using that temporary.
It's a lot like a constructor call, the "MyClass()" part of "MyClass c = MyClass();", except that pointer-to-function types don't actually have constructors. Of course in my code snippet here, "MyClass()" doesn't necessarily create a temporary, because it's an initializer expression. The "MyClass()" in "MyClass().some_method();" is perhaps a closer analogy.
"int()" is another way of saying "int(0)", which is another way of saying "(int)0", which is another way of saying "0". Again, it assigns to a temporary, and if that's the whole statement then the temporary is unused.
If you compile the code in the question with -Wall on GCC, you get a warning "statement has no effect". The code a person doing this might have meant to type, "clean();", wouldn't produce that warning because of course it would have the effect of calling the function. Yet another reason to switch warnings on, and fix 'em properly ;-)
|
292,109
| 1,735,543
|
Outputting to stderr whenever malloc/free is called
|
With Linux/GCC/C++, I'd like to record something to stderr whenever malloc/free/new/delete are called. I'm trying to understand a library's memory allocations, and so I'd like to generate this output while I'm running unit tests. I use valgrind for mem leak detection, but I can't find an option to make it just log allocations.
Any ideas? I'm looking for the simplest possible solution. Recompiling the library is not an option.
|
malloc_hook(3) allows you to globally interpose your own malloc function. (There's __realloc_hook __free_hook etc. as well, I've just left them out for simplicity.)
#include <stdio.h>
#include <malloc.h>
static void *(*old_malloc_hook)(size_t, const void *);
static void *new_malloc_hook(size_t size, const void *caller) {
void *mem;
__malloc_hook = old_malloc_hook;
mem = malloc(size);
fprintf(stderr, "%p: malloc(%zu) = %p\n", caller, size, mem);
__malloc_hook = new_malloc_hook;
return mem;
}
static void init_my_hooks(void) {
old_malloc_hook = __malloc_hook;
__malloc_hook = new_malloc_hook;
}
void (*__malloc_initialize_hook)(void) = init_my_hooks;
$ cat >mem.c <<'EOF'
(the code above)
EOF
$ cc -fPIC -shared -o mem.so mem.c
$ LD_PRELOAD=./mem.so ls
0x7ffc14931adc: malloc(5) = 0xb40010
0x7ffc1492c6b0: malloc(120) = 0xb40030
0x7ffc1497f61a: malloc(12) = 0xb40010
0x7ffc1492be38: malloc(776) = 0xb400b0
…
printf might call malloc, which is why we undo the hook temporarily. Be careful of this if when you hook malloc in any way.
|
292,124
| 292,151
|
Is there any reason not to make a member function virtual?
|
Is there any real reason not to make a member function virtual in C++? Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.
On the other hand, I've been bitten a couple of times with forgetting to make a function virtual that should be virtual. And that seems to be a bigger argument than the performance one. So is there any reason not to make member functions virtual by default?
|
One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default." Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual. Seems to me this would have required more effort in the compiler implementation, and slowed down the adoption of C++ by providing fodder to the performance obsessed (I count myself in that group.)
Another way to read your questions is "Why do C++ programmers do not make every function virtual unless they have very good reasons not to?" The performance excuse is probably the reason. Depending on your application and domain, this might be a good reason or not. For example, part of my team works in market data ticker plants. At 100,000+ messages/second on a single stream, the virtual function overhead would be unacceptable. Other parts of my team work in complex trading infrastructure. Making most functions virtual is probably a good idea in that context, as the extra flexibility beats the micro-optimization.
|
292,450
| 292,582
|
Wrapping Visual C++ in C#
|
I need to do some process injection using C++ but I would prefer to use C# for everything other than the low level stuff. I have heard about "function wrapping" and "marshaling" and have done quite a bit of google searching and have found bits of information here and there but I am still really lacking.
Things I have read in order of usefulness;
http://msdn.microsoft.com/en-us/library/ms235281(VS.80).aspx
http://www.drdobbs.com/cpp/184401742
http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html
How can I wrap all the lower level stuff (native C++) in C# so I can easily command those functions in a language I am more comfortable with, C#?
Any information on the topic is much appreciated.
|
I think P/Invoke is really the most straightforward approach:
Create a DLL in unmanaged C++, containing all the functionality you need to do the injection.
In your C# code, declare some static extern methods, and use the DllImport attribute to point them to your C++ dll. For more details, see the link provided by arul in his answer.
Note that P/Invoke isn't limited to "windows API functions" — you can call functions exposed by any native DLL.
A potential downside of P/Invoke is that you will have to provide the signatures for your C++ functions, possibly specifying some less-than-obvious marshalling. In that case, you could consider constructing a COM server instead of a "plain" DLL, and using COM interop to call your code from C#.
|
292,740
| 292,764
|
C++ reading from a file blocks any further writing. Why?
|
I am implementing a very simple file database. I have 2 basic operations:
void Insert(const std::string & i_record)
{
//create or append to the file
m_fileStream.open(m_fileName.c_str(), std::ios::out | std::ios::app);
if (m_fileStream.is_open())
{
m_fileStream << i_record << "\n";
}
m_fileStream.flush();
m_fileStream.close();
}
/*
* Returns a list with all the items in the file.
*/
std::vector<std::string> SelectAll()
{
std::vector<std::string> results;
m_fileStream.open(m_fileName.c_str(), std::ios::in);
std::string line;
if (m_fileStream.is_open())
{
while (!m_fileStream.eof())
{
getline (m_fileStream, line);
results.push_back(line);
}
}
m_fileStream.close();
return results;
}
the class has m_fileStream and m_fileName as private members.
OK - here's the problem:
If I do something like:
db->Insert("a");
db->SelectAll();
db->Insert("b");
The end result is that the file will contain only "a"; WHY?
NOTE: it seems that getline() will set the fail bit. but why?
|
Change
while (!m_fileStream.eof())
{
getline (m_fileStream, line);
results.push_back(line);
}
to
while (getline (m_fileStream, line))
{
results.push_back(line);
}
Otherwise you will get one additional empty line at the end. eof() will return true only once you tried to read past the end of the file, and not if only the next read would be past the end of the file.
It sets the failbit because getline tries to extract characters from the stream. If there are no characters left (and no '\n' has been seen yet), stream.get(c) to a character will set the failbit. Then getline will set the eofbit and then .eof() will return true, and your loop exits.
If you don't want failbit set, then change your condition from !stream.eof() to stream.peek() != EOF (and make sure there is a trailing newline in your file).
This now is also the solution to your problem: .close() doesn't .clear() your stream, so the failbit still is set if you reopen your file. call stream.clear() after reading your stuff in, and then it works.
|
292,997
| 390,279
|
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?
|
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?
If so how?
Note I know you can use timers instead, but I'd like to know about these socket options in particular.
|
Absolutely! Boost ASIO allows you to access the native/underlying data, which in this case is the SOCKET itself. So, let's say you have:
boost::asio::ip::tcp::socket my_socket;
And let's say you've already called open or bind or some member function that actually makes my_socket usable. Then, to get the underlying SOCKET value, call:
SOCKET native_sock = my_socket.native();
int result = SOCKET_ERROR;
if (INVALID_SOCKET != native_sock)
{
result = setsockopt(native_sock, SOL_SOCKET, <the pertinent params you want to use>);
}
So there you have it! Boost's ASIO lets you do many things more quickly than you otherwise might be able to, but there are a lot of things you still need the normal socket library calls for. This happens to be one of them.
|
293,421
| 293,445
|
C++: Using operator of two intrinsic types as a function object
|
I have a vector-like class that contains an array of objects of type "T", and I want to implement 4 arithmetic operators, which will apply the operation on each item:
// Constructors and other functions are omitted for brevity.
template<class T, unsigned int D>
class Vector {
public:
// Add a value to each item: naive implementation.
void operator += (const T&) {
for (int i = 0; i < D; ++i) {
data[i] += value;
}
}
void operator -= (const T&) { ... }
void operator *= (const T&) { ... }
void operator /= (const T&) { ... }
private:
T items[D];
};
Because operators will contain the same boilerplate code (looping over every element and applying appropriate operation), I thought I could generalize it:
template<class T, unsigned int D>
class Vector {
public:
void operator += (const T& value) { do_for_each(???, value); }
void operator -= (const T& value) { do_for_each(???, value); }
void operator *= (const T& value) { do_for_each(???, value); }
void operator /= (const T& value) { do_for_each(???, value); }
private:
void
do_for_each(std::binary_function<void, T, T>& op, T value) {
std::for_each(data, data + D, std::bind2nd(op, value));
}
T data[D];
};
Now, the problem is, how do I pass an operator that takes two intrinsic types and returns void to do_for_each, as depicted in the example above? C++ does not let me do this trick for intrinsic types ("T::operator+=" will not work if "T" is "int").
|
First, you should really return a reference from your operator+=, since you can later use them to implement operator+, operator- and so on. I will change that accordingly.
Also, your do_for_each has to be a template, since it has to know the precise type of the function object, as binary function objects are not polymorph classes. For the actual operation, you want to use std::transform:
template<class T, unsigned int D>
class Vector {
public:
Vector& operator += (const T& value) {
do_for_each(std::plus<T>(), value);
return *this;
}
Vector& operator -= (const T& value) {
do_for_each(std::minus<T>(), value);
return *this;
}
Vector& operator *= (const T& value) {
do_for_each(std::multiplies<T>(), value);
return *this;
}
Vector& operator /= (const T& value) {
do_for_each(std::divides<T>(), value);
return *this;
}
private:
template<typename BinFun>
void do_for_each(BinFun op, const T& value) {
std::transform(data, data + D, data, std::bind2nd(op, value));
}
T data[D];
};
std::transform will just pass each element to the function object, and assigns the result back to the iterator given as the third argument.
|
293,499
| 293,563
|
What happens if you don't return a value in C++?
|
Yesterday, I found myself writing code like this:
SomeStruct getSomeStruct()
{
SomeStruct input;
cin >> input.x;
cin >> input.y;
}
Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that was returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?
|
Did another SomeStruct get created and initialized somewhere implicitly?
Think about how the struct is returned. If both x and y are 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry's answer mentions how simpler values are returned), so it has to be allocated somewhere. It would be wasteful to use the heap for this, so it has to be allocated on the stack. But it cannot be on the stack frame of your getSomeStruct function, since that is not valid anymore after the function returns.
The compiler instead has the caller tells the called function where to put the result (which is probably somewhere on the stack of the caller), by passing the called function a hidden pointer to the space allocated to it. So, the place where it is being set to zero is on the caller, not on your getSomeStruct function.
There are also optimizations like the "named value return optimization" where extra copies can be elided. So, had you used the missing return, the result would be created directly on the space allocated by the caller, instead of creating a temporary and copying it.
To know more about what is happening, you have to look at the caller function. Is it initializing (to zero) an "empty" SomeStruct to which you later assign the return value of your getSomeStruct function? Or is it doing something else?
|
293,672
| 293,709
|
Reading files larger than 4GB using c++ stl
|
A few weeks back I was using std::ifstream to read in some files and it was failing immediately on open because the file was larger than 4GB. At the time I couldnt find a decent answer as to why it was limited to 32 bit files sizes, so I wrote my own using native OS API.
So, my question then: Is there a way to handle files greater than 4GB in size using std::ifstream/std::ostream (IE: standard c++)
EDIT: Using the STL implementation from the VC 9 compiler (Visual Studio 2008).
EDIT2: Surely there has to be standard way to support file sizes larger than 4GB.
|
Apparently it depends on how off_t is implemented by the library.
#include <streambuf>
__int64_t temp=std::numeric_limits<std::streamsize>::max();
gives you what the current max is.
STLport supports larger files.
|
293,723
| 293,732
|
How could I create a custom windows message?
|
Our project is running on Windows CE 6.0 and is written in C++ . We have some problems with the code , and we are unable to debug . We also found out that if in our application we create threads and try to printf from them , the output won't appear . The only output that will appear is the one from the main thread . I would like to do the following :
create a custom windows message
use as it's WPARAM the address of a char* I want to show on the screen
use as it's LPARAM the length of the char* I want to show on the screen
send the message
process it when it comes , so that it prints the char*
How could I create the custom windows message ? What are the types of WPARAM and LPARAM ? Is it possible to do what I just wrote ?
Thanks
|
It's certainly possible to do what you describe. You don't need to actually do anything to create a custom message for communication within your application: just make sure that the code that sends the message and the code that receives the message agree on what the message number actually is, and use a message number that doesn't overlap with any of the numbers Windows uses. There is a RegisterWindowMessage() function, but that's only needed to get a message number that's unique across the entire operating system, so used for inter-process communication.
The simplest way to achieve this is to just have a header file somewhere containing your custom message numbers, starting with WM_USER and numbering upwards, like so:
#define WM_FIRST_CUSTOM_MSG (WM_USER+0)
#define WM_SECOND_CUSTOM_MSG (WM_USER+1)
The WPARAM and LPARAM types are defined when you include "windows.h", so can have different types on different systems. For 32-bit operating systems, they are both usually 32-bit integers. If you're just using the message for testing purposes, that's usually good enough, and you can stick whatever you want in there. For production code, though, you should be more careful: WPARAM is really for "integer-like" data, and LPARAM for "pointer-like" data. In Win64, for example, LPARAM is long enough to hold a 64-bit pointer, but WPARAM only holds a 32-bit integer. For passing more data than just an integer and a pointer, I'd use lParam to pass a pointer to some sort of structure containing all my arguments.
Having said all that, it sounds like a complicated way of getting debugging output. Have you tried using the OutputDebugString() API call? Or debugging the thread's printf() call?
|
293,774
| 293,781
|
How to create a QWidget with a HWND as parent?
|
With wxWidgets I use the following code:
HWND main_window = ...
...
wxWindow *w = new wxWindow();
wxWindow *window = w->CreateWindowFromHWND(0, (WXHWND) main_window);
How do I do the same thing in Qt? The HWND is the handle of the window I want as the parent window for the new QtWidget.
|
Use the create method of QWidget.
HWND main_window = ...
...
QWidget *w = new QWidget();
w->create((WinId)main_window);
|
293,799
| 293,971
|
How do I use std::tr1::mem_fun in Visual Studio 2008 SP1?
|
The VS2008 SP1 documentation talks about std::tr1::mem_fun.
So why, when I try and use std::tr1::mem_fun, why do I get this compile error?:
'mem_fun' : is not a member of 'std::tr1'
At the same time, I can use std::tr1::function without problems.
Here is the sample code I am trying to compile, which is supposed to call TakesInt on an instance of Test, via a function<void (int)>:
#include "stdafx.h"
#include <iostream>
#include <functional>
#include <memory>
struct Test { void TakesInt(int i) { std::cout << i; } };
void _tmain()
{
Test* t = new Test();
//error C2039: 'mem_fun' : is not a member of 'std::tr1'
std::tr1::function<void (int)> f =
std::tr1::bind(std::tr1::mem_fun(&Test::TakesInt), t);
f(2);
}
I'm trying to use the tr1 version of mem_fun, because when using std::mem_fun my code doesn't compile either! I can't tell from the compiler error whether the problem is with my code or whether it would be fixed by using tr1's mem_fun. That's C++ compiler errors for you (or maybe it's just me!).
Update: Right. The answer is to spell it correctly as mem_fn!
However when I fix that, the code still doesn't compile.
Here's the compiler error:
error C2562:
'std::tr1::_Callable_obj<_Ty,_Indirect>::_ApplyX' :
'void' function returning a value
|
Change it to this:
std::tr1::function<void (int)> f =
std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1);
f(2);
The binder requires the int argument. So you have to give it a placeholder which stands for the integer argument that the generated function object needs.
Btw: I'm not sure whether you already know this or not. But you don't need that mem_fn for this. Just change it to
std::tr1::function<void (int)> f =
std::tr1::bind(&Test::TakesInt, t, std::tr1::placeholders::_1);
f(2);
|
293,857
| 293,868
|
Why does this const member function allow a member variable to be modified?
|
class String
{
private:
char* rep;
public:
String (const char*);
void toUpper() const;
};
String :: String (const char* s)
{
rep = new char [strlen(s)+1];
strcpy (rep, s);
}
void String :: toUpper () const
{
for (int i = 0; rep [i]; i++)
rep[i] = toupper(rep[i]);
}
int main ()
{
const String lower ("lower");
lower.toUpper();
cout << lower << endl;
return 0;
}
|
A const member function, is a member function that does not mutate its member variables.
const on a member function does not imply const char *. Which would mean that you can't change the data in the address the pointer holds.
Your example does not mutate the member variables themselves.
A const on a member function, will ensure that you treat all of your member variables as const.
That means if you have:
int x;
char c;
char *p;
Then you will have:
const int x;
const char c;
char * const p; //<-- means you cannot change what p points to, but you can change the data p points to
There are 2 types of const pointers. A const member function uses the one I've listed above.
A way to get the error you want:
Try changing:
char * rep;
to:
char rep[1024];
And remove this line:
rep = new char [strlen(s)+1];
It will throw the error you are expecting (can't modify members because of const keyword)
Because there is only 1 type of const array. And that means you cannot modify any of its data.
Now the whole system is actually broken with the following example:
class String
{
private:
char rep2[1024];
char* rep;
...
String :: String (const char* s)
{
rep = rep2;
strcpy (rep, s);
}
So the lesson to learn here is that the const keyword on member functions does not ensure that your object will not change at all.
It only ensures that each member variable will be treated as const. And for pointers, there is a big diff between const char * and char * const.
Most of the time a const member function will mean that the member function will not modify the object itself, but this is not always the case, as the above example shows.
|
293,988
| 293,996
|
Generic vector of vectors in C++
|
Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?
Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push_back), so they can't just take a generic type supporting [][].
What I want to do is:
template<typename T>
typedef vector< vector<T> > vecvec;
vecvec<int> intSequences;
vecvec<string> stringSequences;
but of course that's not possible, since typedef can't be templated.
#define vecvec(T) vector< vector<T> >
is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers.
|
You want to have template-typedefs. That is not yet supported in the current C++. A workaround is to do
template<typename T>
struct vecvec {
typedef std::vector< std::vector<T> > type;
};
int main() {
vecvec<int>::type intSequences;
vecvec<std::string>::type stringSequences;
}
In the next C++ (called c++0x, c++1x due to 2010), this would be possible:
template<typename T>
using vecvec = std::vector< std::vector<T> >;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.