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 |
|---|---|---|---|---|
1,900,868 | 1,900,952 | Transitioning from desktop app written in C++ to a web-based app | We have a mature Windows desktop application written in C++. The application's GUI sits on top of a windows DLL that does most of the work for the GUI (it's kind of the engine). It, too, is written in C++. We are considering transitioning the Windows app to be a web-based app for various reasons.
What I would like to avoid is having to writing the CGI for this web-based app in C++. That is, I would rather have the power of a 4G language like Python or a .NET language for creating the web-based version of this app.
So, the question is: given that I need to use a C++ DLL on the backend to do the work of the app what technology stack would you recommend for sitting between the user's browser and are C++ dll? We can assume that the web server will be Windows.
Some options:
Write a COM layer on top of the windows DLL which can then be access via .NET and use ASP.NET for the UI
Access the export DLL interface directly from .NET and use ASP.NET for the UI.
Write a custom Python library that wraps the windows DLL so that the rest of the code can be written.
Write the CGI using C++ and a C++-based MVC framework like Wt
Concerns:
I would rather not use C++ for the web framework if it can be avoided - I think languages like Python and C# are simply more powerful and efficient in terms of development time.
I'm concerned that my mixing managed and unmanaged code with one of the .NET solutions I'm asking for lots of little problems that are hard to debug (purely anecdotal evidence for that)
Same is true for using a Python layer. Anything that's slightly off the beaten path like that worries me in that I don't have much evidence one way or the other if this is a viable long term solution.
|
See also Can a huge existing
application be ported to the web?
How?
Sorry there are no good solutions, just less bad ones....
Firstly as you already develop for windows I am assuming that you are used to using the Microsoft development tools, I would not give the same answer for a desktop application that is coming from unix (or Mac).
Some random thoughts and pointers.
I would make use of Asp.net most likely Aps.net MVC.
I would try to wrap in C++ classes in some nice high level .net class, maybe using Managed C++ / CLI.
Using COM is likely to be a lot of work on the C++ side and does not make the .NET easy, so I would avoid COM in favour of managed C++ or pinvoke (However if you are allready using COM on the C++ side, this it is an option, provided you are using the subset of COM that VB6 could cope with).
.NET can't access none managed C++ object, but it can access simple C function using Pinvoke, so whatever you do some sort of bridging layer will be needed on the C++ site.
See if you can use Silverlight rather than the web, if you are able to (install issues etc) it will save you a lot of development time. (And lets you target Microsoft Phones as well)
Check that the business case for a “port to the web” is very strong and it will take a lot longer then you think!, Is hosting with terminal server etc an option for your customers?
Think about threading and multi user access, e.g. does your dll assume it is only being used by one user?
Just because you are working on a new web version, you will still get customers demanding changes to the desktop version even after you have shipped the web version. I have found in the past that current customers don’t always wish to move to a web app.
(Sorry I don’t know match about Python, however if you don’t already have skills in it I would say stick on the Microsoft stack as you already know the Microsoft debugger etc)
(I think of porting complex applications to the web as a very big pain, it is best to avoid pain when possible however sometimes you are given no option and just have to minimize the pain. If you have never worked on large applications that are in the process (normally many years work) of being ported to the web, you just don’t know what you are letting yourself in for!)
|
1,900,924 | 1,901,917 | Behaviour of std::partition when called on empty container? | I ran into a problem when calling std::partition on an empty container (std::list).
std::list<int>::iterator end_it = std::partition(l.begin(), l.end(), SomeFunctor(42));
std::list<int>::iterator it = l.begin();
while (it != end_it)
{
// do stuff
}
If the list is empty, std::partition returns an iterator, that is not equal
to l.end(). Is this the default behaviour?
| Right now, there really is no good answer. The Library Working Group of the C++ committee issue number 1205 covers exactly this question. That issue includes both a primary and an alternative proposed resolution but neither has been accepted or rejected yet (and I don't like either one).
Since the standard doesn't give an unambiguous definition of the result of applying an algorithm to an empty range, I'd say the result of doing so is currently undefined. I think there's some hope that it'll be defined in the next version of the standard, but for now it's really not. Even when it is, from a practical viewpoint it'll probably be better to avoid it at least for a while, because it may be a while before compilers conform in this respect (though it should usually be a fairly easy fix).
Edit, mostly in response to Martin B's comment: the issue is listed for [alg.partitions], which includes both std::partition and std::stable_partition. Unfortunately, the proposed wording does not seem to directly address either one. The paragraph it cites is (at least in N2960) in the description of std::is_paritioned, which is pretty much what Martin B described, even though he used the wrong name for it. Worse, the primary proposed resolution is in the form of non-normative notes.
As I said, though, I don't really like either proposed resolution. The primary tries to place requirements in non-normative notes. Such notes are fine if they clarify requirements that are really already present elsewhere, but might be hard to find. In this case, I'm pretty sure the requirements really aren't present. The alternative resolution is better, but fails to address the core question of whether an empty range is a valid range.
IMO, a better resolution would start at §24.1/7. This already tells us that: "A range [i, i) is an empty range;..." I think it should add normative language to explicitly state that an empty range either is or is not a valid range. If it's not a valid range, nothing else needs to be added -- it's already explicit that applying an algorithm to an invalid range gives undefined behavior.
If an empty range is valid, then normative wording needs to be added to define the results for applying each algorithm to an empty range. This would answer the basic question, then state what that answer implies for each specific algorithm.
|
1,901,049 | 1,901,677 | Boost (v1.33.1) Thread Interruption | How can I interrupt a sleeping/blocked boost::thread?
I am using Boost v1.33.1, upgrading is not an option.
Thank you.
| A quick perusal of the documentation for boost.thread in 1.33 suggests that there is no portable way to achieve interruption. Thread interruption was introduced (for threads in one of the boost "interruption points") in 1.35.
As a result the only option I can think of is to use signals (which aren't in 1.33 either, so you'll need to fall back on, for example, pthreads) combined with time-outs on any methods that are blocking. Basically use signals to wake threads that are asleep by having them sleep waiting for the signal and timeouts on blocking threads to have them wake up and check to see if they should exit. Unfortunately this is a highly undesirable solution, and to some extent amounts to what newer versions of boost do internally anyway.
If you're using boost.thread, then you should consider upgrading to a more recent version for other projects because 1.33 doesn't support the vast majority of constructs that are essential for multi-threading.
|
1,901,162 | 1,901,358 | How to tunnel TCP over reliable UDP? | Assume I have a reliable UDP library, and want to tunnel arbitrary TCP connections over it. This is my current approach to doing so, but I feel that it may not be very efficient. Any suggestions are very welcome.
Client establishes a reliable UDP connection to server.
Client runs a local SOCKS5 proxy, which receives data from any app that connects to it and forwards it through the reliable UDP connection. Each packet includes a 4-byte id unique to each SOCKS connection.
Server receives data. If the 4-byte id is new, it makes a new connection to its local TCP socket and sends the data, and spawns a new thread which receives any replies from the server and forwards them through the reliable UDP connection with the appropriate id. If the 4-byte id is old, it simply sends the data over the existing TCP connection.
Client receives data, sending it over the existing SOCKS connection to whatever app started it.
Right now, this seems to work for making simple HTML requests from a browser, but since the server isn't directly connected to the client, it is unable to tell when the client terminates a connection. Is there a better way to do this?
EDIT: No, this is not homework. And please don't bother replying if you aren't aware of the advantages of reliable UDP libraries, or for that matter, haven't heard of them before. Thanks.
| The most efficient way is when the two endpoints directly communicate to each other. If they communicate with different protocols, you need at least one proxy / gateway / traffic converter / whatever. In this case, there is no way around two of these converters, as you now have 3 parts involved: End point client, network traffic, endpoint server. I don't see how you could make it more efficient under the given circumstances.
As for the terminated connections, if you use a tunnel then use it for all traffic, i.e. communicate all kinds of requests of both client and server to the other side. If a termination can't be communicated to the server, then the problem is sitting on the client side -- the client end point does not communicate its termination to the client tunnel entry. If it would, then you can transfer this termination to the server.
|
1,901,483 | 1,901,511 | Min and Max values for integer variable at compile time in C++ | Is there a simple, clean way of determining at compile time the max and min values for a variable of some (otherwise unknown at the moment) integer variable or type? Using templates?
For example:
// Somewhere in a large project is:
typedef unsigned long XType;
typedef char YType;
// ...
// Somewhere else
XType a;
YType b;
LONGLONG c,d,e,f;
c = MinOfType(a); // Same as c = 0;
d = MaxOfType(a); // Same as d = 0xffffffff;
e = MinOfType(b); // Same as e = -128;
f = MaxOfType(b); // Same as f = 127;
// Also would be nice
e = MinOfType(YType); // Same as e = -128; // Using the typename directly
// Or perhaps
e = MinOfType<YType>(); // Same as e = -128; // Using the typename directly
| Check out boost integer_traits.
|
1,901,682 | 1,901,813 | C++ Data Timeout with Blocking Call | I have a main loop which is fully data-driven: it has a blocking call to receive data and stores it as the 'most recent' (accessed elsewhere). Each piece of data has an associated lifespan, after which the data timesout and can no longer be considered valid. Each time I receive data I reset the timeout.
Unfortunately I can currently only test the data validity when the main thread is woken by the arrival of new data. I need to be able to trigger an event if/when the data expires, unless I receive new data in the meantime.
Please can anyone suggest a solution?
If it helps, I have Boost v1.33.1 installed - but cannot update to a more recent version.
| Since the expiration of data is an asynchronous event, you'll need to use an asynchronous timer. As you're using boost, you may want to look into Boost.Asio, which provides you with deadline_timer objects that can be used in conjunction with callback handlers. (See here for more information.) The callback handler will be invoked when the timer expires, which will allow you to check the validity of your data.
Edit: Ahh...I just noticed you're stuck with Boost 1.33.1, which doesn't have Asio. Well, if you're allowed to use other libraries you can use the non-boost version of Asio, or else you'll need to rely on OS-specific techniques to implement asynchronous timers. You don't specify your OS, but on POSIX-compliant systems you can use select/poll for timeouts.
Actually, you can also use a background thread which sleeps until the next piece of data expires, then wakes up and checks the state of all the data, and goes back to sleep until the next piece of data expires. You'd just need to be careful that you synchronize everything properly to avoid race conditions.
|
1,901,768 | 1,901,831 | Implicit invocation of operator [C++] | I defined two classes:
class Token_
{
public:
virtual char operator*()const = 0;//this fnc cannot run implicitly
protected:
Token_()
{ }
Token_(const Token_&);
Token_& operator=(const Token_&);
};
and second:
class Operator : public Token_
{
public:
Operator(const char ch):my_data_(token_cast<Operator_enm>(ch))
{ }
Operator_enm get()const
{
return my_data_;
}
Operator_enm set(const Operator_enm& value)
{
Operator_enm old_value = get();
my_data_ = value;
return old_value;
}
char operator*()const//this operator has to be invoke explicitly
{
return static_cast<char>(my_data_);
}
private:
Operator_enm my_data_;
};
and later on in program I have something like this:
template<class R>
R Calculator::expr_()const
{
Token_* token = read_buffer_();
switch (*token)//here if I use explicit call of operator*() it works
{
case PLUS:
{
R result ;//not defined yet
return result;
}
case MINUS:
{
R result ;//not defined yet
return result;
}
default:
cerr << "Bad expr token.";
}
}
Why this call of operator*() can't be implicit? Is there any way to make it implicit?
Thank you.
| token is a pointer to a Token_ object, not a Token_ object itself, thus the * operator in the switch statement dereferences only the pointer (thereby only obtaining the object), but doesn't then continue to call the operator you defined.
Try instead:
switch(*(*token)) {
The use of your custom operator * might be a bit confusing now though.
Another options is to alter read_buffer_() such that you can do the following:
Token_ token = read_buffer_(); // NOTE: read_buffer_() returns a Token_ object directly
switch (*token)//here if I use explicit call of operator*() it works
In that case, Token_ objects mimic pointers, and you wouldn't return pointer to pointers normally either.
|
1,901,781 | 1,901,991 | SSE2 - "The system cannot execute the specified program" | I recently developed a Visual C++ console application which uses inline SSE2 instructions. It works fine on my computer, but when I tried it on another, it returns the following error:
The system cannot execute the specified program
Note that the program worked on the other computer before introducing the SSE2 code.
Any suggestions?
PS: It works when I compile the code on the other computer and run it. I think it has something to do with the manifest from what I've scrounged off the net.
| Most likely the use of the SSE2 instructions is requiring a DLL which isn't present on the second system.
Here's a blog entry on how to figure out exactly which one:
How to Debug 'The System cannot Execute the specified program' message
|
1,902,003 | 1,902,073 | Does the visual studio 2008 profiler work with unmanaged C++? | I know that VS 2008 Team Edition has a profiler, but I'm also aware of the recent trend they have at Microsoft of completely ignoring unmanaged languages (what's the last time unmanaged C++ got something cool in the IDE?!).. For example I know for a fact that the IDE "Unit Tests" and "Code Metrics" features don't work with unmanaged code.
I tried to google but didn't find any info; so, does anyone know if it works or not?
| Yes, it works with native code.
|
1,902,464 | 1,902,940 | Is there a better way to bring names into class scope other than to typedef them? | I keep running into this issue:
class CCreateShortcutTask : public CTask
{
public:
CCreateShortcutTask(
CFilename filename, // shortcut to create (or overwrite)
Toolbox::Windows::CShellLinkInfo definition // shortcut definition
)
...
Having to spell out Toolbox::Windows::CShellLinkInfo seems highly questionable to me. This is in a header, so I surely don't wish to issue a using namespace declaration or I'll drag that namespace into every client file that includes this header.
But I don't seriously want to have to fully name these things in the class interface itself. I'd really love to be able to do something like:
class CCreateShortcutTask : public CTask
{
using namespace Toolbox::Windows;
-or possibly-
using Toolbox::Windows::CShellLinkInfo;
public:
CCreateShortcutTask(
CFilename filename, // shortcut to create (or overwrite)
CShellLinkInfo definition // shortcut definition
)
...
But these seem to be illegal constructs.
Any ideas how to accomplish this?
EDIT: I have asked a broader version of this question here
| I think there is a confusion on typedefs.
Using private typedefs is perfectly suitable (and often used). This relies on the fact that in C++ a typedef does not introduce a new type, but a synonym!
namespace VeryLongNamespaceYoullNeverWantToSeeAgain
{
class SuchAStupidNameShouldBeBanned
{
public:
typedef xxx iterator;
typedef zzz value_type;
static std::string Print(value_type);
private:
};
void destroy(SuchAStupidNameShouldBeBanned&);
}
namespace short
{
class MyStruct
{
typedef VeryLongNamespaceYoullNeverWantToSeeAgain::SuchAStupidNameShouldBeBanned Stupid;
public:
void destroyStupid()
{
Stupid::iterator it = m_stupid.begin(), end = m_stupid.end();
std::cout << "Getting rid of ";
for (; it != end; ++it) std::cout << Stupid::Print(*it) << " ";
std::cout << std::endl;
destroy(m_stupid);
}
private:
Stupid m_stupid;
};
}
Thus, private typedefs don't bother:
name lookup: destroy is correctly invoked
use of inner typedefs: iterator is found
use of static methods: Print is found
So you can really use them without many fuss. Furthermore they don't pollute the global space since they are inner to the class and though visible cannot be manipulated by the client directly so he does not rely on them.
Within the source file, you can use namespace aliasing and using directives (not using namespaces please) more liberally, so it's less of an issue.
|
1,902,810 | 1,903,311 | What shall I do while waiting in a thread | I have a main program which creates a collection of N child threads to perform some calculations. Each child is going to be fully occupied on their tasks from the moment their threads are created till the moment they have finished. The main program will also create a special (N+1)th thread which has some intermittent tasks to perform. When certain conditions are met (like a global variable takes on a certain value) the special thread will perform a calculation and then go back to waiting for those conditions to be met again. It is vital that when the N+1th thread has nothing to do, it should not slow down the other processors.
Can someone suggest how to achieve this.
EDIT:
The obvious but clumsy way would be like this:
// inside one of the standard worker child threads...
if (time_for_one_of_those_intermittent_calculations_to_be_done())
{
global_flag_set = TRUE;
}
and
// inside the special (N+1)th thread
for(;;)
{
if (global_flag_set == TRUE)
{
perform_big_calculation();
global_flag_set = FALSE;
}
// sleep for a while?
}
| A ready-to-use condition class for WIN32 ;)
class Condition {
private:
HANDLE m_condition;
Condition( const Condition& ) {} // non-copyable
public:
Condition() {
m_condition = CreateEvent( NULL, TRUE, FALSE, NULL );
}
~Condition() {
CloseHandle( m_condition );
}
void Wait() {
WaitForSingleObject( m_condition, INFINITE );
ResetEvent( m_condition );
}
bool Wait( uint32 ms ) {
DWORD result = WaitForSingleObject( m_condition, (DWORD)ms );
ResetEvent( m_condition );
return result == WAIT_OBJECT_0;
}
void Signal() {
SetEvent( m_condition );
}
};
Usage:
// inside one of the standard worker child threads...
if( time_for_one_of_those_intermittent_calculations_to_be_done() ) {
global_flag_set = TRUE;
condition.Signal();
}
// inside the special (N+1)th thread
for(;;) {
if( global_flag_set==FALSE ) {
condition.Wait(); // sends thread to sleep, until signalled
}
if (global_flag_set == TRUE) {
perform_big_calculation();
global_flag_set = FALSE;
}
}
NOTE: you have to add a lock (e.g. a critical section) around global_flag_set. And also in most cases the flag should be replaced with a queue or at least a counter (a thread could signal multiple times while 'special' thread is performing its calculations).
|
1,902,832 | 1,902,900 | resize versus push_back in std::vector : does it avoid an unnecessary copy assignment? | When invoking the method push_back from std::vector, its size is incremented by one, implying in the creation of a new instance, and then the parameter you pass will be copied into this recently created element, right? Example:
myVector.push_back(MyVectorElement());
Well then, if I want to increase the size of the vector with an element simply using its default values, wouldn't it be better to use the resize method instead? I mean like this:
myVector.resize(myVector.size() + 1);
As far as I can see, this would accomplish exactly the same thing but would avoid the totally unnecessary assignment copy of the attributes of the element.
Is this reasoning correct or am I missing something?
| At least with GCC, it doesn't matter which you use (Results below). However, if you get to the point where you are having to worry about it, you should be using pointers or (even better) some form of smart pointers.. I would of course recommend the ones in the boost library.
If you wanted to know which was better to use in practice, I would suggest either push_back or reserve as resize will resize the vector every time it is called unless it is the same size as the requested size. push_back and reserve will only resize the vector if needed. This is a good thing as if you want to resize the vector to size+1, it may already be at size+20, so calling resize would not provide any benefit.
Test Code
#include <iostream>
#include <vector>
class Elem{
public:
Elem(){
std::cout << "Construct\n";
}
Elem(const Elem& e){
std::cout << "Copy\n";
}
~Elem(){
std::cout << "Destruct\n";
}
};
int main(int argc, char* argv[]){
{
std::cout << "1\n";
std::vector<Elem> v;
v.push_back(Elem());
}
{
std::cout << "\n2\n";
std::vector<Elem> v;
v.resize(v.size()+1);
}
}
Test Output
1
Construct
Copy
Destruct
Destruct
2
Construct
Copy
Destruct
Destruct
|
1,902,976 | 1,906,674 | MSVC - Any way to check if function is actually inlined? | I have to check whether a function is being inlined by the compiler. Is there any way to do this without looking at assembly (which I don't read). I have no choice in figuring this out, so I would prefer if we could not discuss the wisdom of doing this. Thanks!
| Generate a "MAP" file. This gives you the addresses of all non-inlined functions. If your function appears in this list, it's not inlined, otherwise it's either inlined or optimized out entirely (e.g. when it's not called at all).
|
1,903,008 | 1,903,614 | Why not call FreeLibrary from entry point function? | I'm writing a DLL that needs to call a separate DLL dynamically multiple times. I would like to keep the callee loaded and then just unload it when my DLL is unloaded. But according to Microsoft, that's a bad idea.
The entry point function should only
perform simple initialization tasks
and should not call any other DLL
loading or termination functions. For
example, in the entry point function,
you should not directly or indirectly
call the LoadLibrary function or the
LoadLibraryEx function. Additionally,
you should not call the FreeLibrary
function when the process is
terminating.
Here's the offending code. Can somebody explain why I shouldn't call LoadLibrary and FreeLibrary from my DLL's entry point?
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_DETACH :
if (hLogLib != NULL) FreeLibrary(hLogLib);
break;
}
return TRUE;
}
| I think I've found the answer.
The entry-point function should
perform only simple initialization or
termination tasks. It must not call
the LoadLibrary or LoadLibraryEx
function (or a function that calls
these functions), because this may
create dependency loops in the DLL
load order. This can result in a DLL
being used before the system has
executed its initialization code.
Similarly, the entry-point function
must not call the FreeLibrary function
(or a function that calls FreeLibrary)
during process termination, because
this can result in a DLL being used
after the system has executed its
termination code.
|
1,903,055 | 1,903,142 | Inheriting from a virtual template class in C++ | How do I inherit from a virtual template class, in this code:
// test.h
class Base {
public:
virtual std::string Foo() = 0;
virtual std::string Bar() = 0;
};
template <typename T>
class Derived : public Base {
public:
Derived(const T& data) : data_(data) { }
virtual std::string Foo();
virtual std::string Bar();
T data() {
return data_;
}
private:
T data_;
};
typedef Derived<std::string> DStr;
typedef Derived<int> DInt;
// test.cpp
template<typename T>
std::string Derived<T>::Foo() { ... }
template<typename T>
std::string Derived<T>::Bar() { ... }
When I try to use the DStr or DInt, the linker complain that there are unresolved externals, which are Derived<std::string>::Foo() and Derived<std::string>::Bar(), and the same for Derived<int>.
Did I miss something in my code?
EDIT:
Thanks all. It's pretty clear now.
| You need to define template<typename T> std::string Derived<T>::Foo() { ... } and template<typename T>
std::string Derived<T>::Bar() { ... } in the header file. When the compiler is compiling test.cpp it doesn't know all the possible values of T that you might use in other parts of the program.
I think there are some compilers that have connections between the compiling and linking steps that notice references to missing template instantiations and go instantiate them from the .cpp file where they are declared. But I don't know which they are, and the functionality is exceedingly rare to find.
If you define them in the header file most compilers will emit them as a 'weak' symbol into every compilation unit in which they're referenced. And the linker will toss out all except for one definition of the weak symbol. This causes extra compilation time.
Alternately, there are syntaxes for explicitly instantiating templates and forcing the compiler to emit definitions right there. But that requires you to be aware of all the values T could possibly have and you will inevitably miss some.
|
1,903,066 | 1,903,522 | Wrapping a PropertySheet; how to handle callbacks? | I'm writing an (unmanaged) C++ class to wrap the Windows PropertySheet. Essentially, something like this:
class PropSheet {
PROPSHEETHEADER d_header;
public:
PropSheet(/* parameters */);
INT_PTR show();
private:
static int CALLBACK *propSheetProc(HWND hwnd, UINT msg, LPARAM lParam);
};
The constructor just initializes the d_header member:
PropSheet::PropSheet(/* parameters */) {
d_header.dwSize = sizeof(PROPSHEETHEADER);
d_header.dwFlags = PSH_USECALLBACK;
// ...
d_header.pfnCallback = &propSheetProc;
// ...
}
After which I can show it, modally, with:
INT_PTR PropSheet::show() {
return PropertySheet(&d_header);
}
Now the problem is, because the callback is static, that it cannot access the wrapper class. If this were a normal window, with a WindowProc instead of a PropSheetProc, I could attach some extra data to the window using cbWndExtra in WNDCLASS, in which I could store a pointer back to the wrapper, like in this article. But property sheets do not offer this functionality.
Furthermore, because the property sheet is shown modally, I can execute no code between the creation and destruction of the actual window, except when that code is executed through the callback or one of the sheets's window procedures.
The best solution I've come up with so far is to, right before showing the property sheet, store a pointer to the wrapper class inside a global variable. But this assumes that I'll only be showing one property sheet at a time, and is quite ugly anyway.
Does anyone have a better idea how to work around this?
| As you are showing the property sheet modally, you should be able to use the parent window (i.e. its handle) of the property sheet to map to an instance, using ::GetParent() on the hwndDlg parameter of PropSheetProc().
|
1,903,173 | 1,903,724 | Problem assigninging values to a struct in C++ to a structure passed from C# | I have a function in C# that is passing an array of structures into a DLL written in C++. The struct is a group of ints and when I read out the data in the DLL all the values come out fine. However if I try to write to the elements from C++ the values never show up when I try to read then back in C#.
C#
[StructLayout(LayoutKind.Sequential)]
struct Box
{
public int x;
public int y;
public int width;
public int height;
}
[StructLayout(LayoutKind.Sequential)]
struct Spot
{
public int x;
public int y;
}
static void TestCvStructs()
{
int len = 100;
Box[] r = new Box[len];
Spot[] p = new Spot[len];
for (int i = 0; i < len; i++)
{
r[i].x = i*10;
r[i].y = i * 200;
r[i].width = r[i].x * 10;
r[i].height = r[i].y * 100 + r[i].x * 5;
p[i].x = i * 8;
p[i].y = i * 12;
}
PassCvStructs(len, r, p);
for (int i = 0; i < len; i++)
{
Console.WriteLine("Point/x:{0} Boxes/x{1}", p[i].x, r[i].x );
}
}
[DllImport(dll)]
private static extern int PassSomeStructs(int count, Box[] boxes, Spot[] points);
C++
typedef struct Box
{
int x;
int y;
int width;
int height;
} Box;
typedef struct Spot
{
int x;
int y;
} Spot;
CPPDLL_API int PassSomeStructs(int arrayLength, Box *boxes, Spot *points)
{
for(int i = 0; i < arrayLength; ++i)
{
printf("Group:%i\n", i);
printf("Rect - x:%i y:%i width:%i length:%i\n", boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
printf("Point - x:%i y:%i\n", points[i].x, points[i].y);
printf("\n");
points[i].x = 3;
boxes[i].x = 1;
}
return 0;
}
| I found the answer posted to another question: How to marshall array of structs in C#?
When marshaling apparently the default is to marshal the parameters as In. Otherwise they need to be explicitly declared as Out or In, Out. After specifying that explicitly my code the example now works.
Thanks to his Skeetness for the answer and to antonmarkov for the exposure to the MarshalAs.
private static extern int PassSomeStructs(int count, [In, Out] Box[] boxes, [In, Out] Spot[] points);
|
1,903,190 | 1,903,281 | Optimal way to perform a shift operation on an array | Suppose I have an array
unsigned char arr[]= {0,1,2,3,4,5,6,7,8,9};
Is there a way to perform shift operation on them besides just copying them all into another array. We can easily do it using linked lists but I was wondering if we can use a shift operator and get work done faster.
Note: The data in this question is just an example. The answer should be irrecpective of the data in the array.
| If you want a circular shift of the elements:
std::rotate(&arr[0], &arr[1], &arr[10]);
... will do the trick. You'll need to #include the algorithm header.
|
1,903,248 | 1,905,486 | C++ client for Java RMI? Or any other way to use Java from C++? | We need to use a Java library from C++ code. An idea that I had is that if we could build a C++ client for Java RMI (ideally using some framework or wizard), than we could run the Java lib as a separate server. This seem cleaner than trying to run Java VM within a C++ application.
Alternatively, if you have any other idea on how to use Java from C++, I'd be glad to hear. We work on Linux.
thanks a lot,
David
| JNI was the intended solution to the problem of C/C++ to Java integration. It's not difficult.
Message Queues are better for larger grained interactions, or remote interactions where the message queue is accessible over the network.
CORBA and RMI were also intended to be network access mechanisms.
From your description you don't want that. You want to consume a Java library in C++, and to do that, you use JNI.
How to start the JVM and invoke a Java method, from C++ (JDK doc)
|
1,903,303 | 1,903,325 | xerces-c++ compile/linking question | After installing Xerces-C++ (XML library):
./configure --disable-shared
./make
./make-install
ldconfig
And writing the simple program (xmlval.cpp):
#include <stdio>
#include <xercesc/dom/DOM.hpp>
int main()
{
std::cout << "HI" << std::endl;
}
And compiling:
/usr/bin/g++ -L/usr/local/lib -I/usr/local/include -o xmlval xmlval.cpp /usr/local/lib/libxerces-c.a
The compile result is a bunch of lines like:
/usr/local/lib/libxerces-c.a(CurlNetAccessor.o): In function `xercesc_3_0::CurlNetAccessor::cleanupCurl()':
/home/stullbd/xerces-c-3.0.1/src/xercesc/util/NetAccessors/Curl/CurlNetAccessor.cpp:78: undefined reference to `curl_global_cleanup'
/usr/local/lib/libxerces-c.a(CurlNetAccessor.o): In function `xercesc_3_0::CurlNetAccessor::initCurl()':
/home/stullbd/xerces-c-3.0.1/src/xercesc/util/NetAccessors/Curl/CurlNetAccessor.cpp:70: undefined reference to `curl_global_init'
/usr/local/lib/libxerces-c.a(CurlURLInputStream.o): In function `~CurlURLInputStream':
/home/stullbd/xerces-c-3.0.1/src/xercesc/util/NetAccessors/Curl/CurlURLInputStream.cpp:168: undefined reference to `curl_multi_remove_handle'
Any thoughts on this?
| You seem to miss linking with curl, try adding -lcurl.
|
1,903,532 | 1,903,567 | Set a file wide breakpoint in gdb | I'm trying to understand how a piece of code is working. I've enabled a breakpoint for a function, but it looks like it never gets hit. So, I'd like to break whenever ANY function within this class is invoked. Is this possible?
Thanks!
| Try rbreak regex - for example:
rbreak ^MyClass::
Noteworthy fact:
There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
|
1,903,846 | 1,903,879 | C++ convert decimal hours into hours, minutes, and seconds | I have some number of miles and a speed in MPH that I have converted into the number of hours it takes to travel that distance at that speed. Now I need to convert this decimal number into hours, minutes, and seconds. How do I do this? My best guess right now is:
double time = distance / speed;
int hours = time; // double to integer conversion chops off decimal
int minutes = (time - hours) * 60;
int seconds = (((time - hours) * 60) - minutes) * 60;
Is this right? Is there a better way to do this? Thanks!
| I don't know c++ functions off the top of my head, however this "psuedocode" should work.
double time = distance / speed;
int hours = time;
double minutesRemainder = (time - hours) * 60;
int minutes = minutesRemainder;
double secondsRemainder = (minutesRemainder - minutes) * 60;
int seconds = secondsRemainder;
Corrected not needing floor.
As far as the comment about it not working for negative times, you can't have a negative distance in physics. I'd say that would be user input error, not coder error!
|
1,903,917 | 1,903,946 | Compiling a static lib inside a exe | I have a dll and an exe, both of which I have the sources to.
For the DLL I have compiled completely statically and therefore, I would assume that the the .lib is also static. However, when I include that lib in my C++ VC++ 2008 project under Linker > Input > Additional Dependencies . I set the compile mode to /MT (multi-threaded) for the exe.
Everything compiles, but when I try to run the exe, it asks for the dll! To the best of my (limited) understanding, that shouldn't be happening.
Why should I do?
| The 'compile mode' setting that you are referring to is the setting for the runtime library that gets linked with whatever library or executable you produce.
If your project is set up to produce a DLL (check the main project page), then it'll still produce a DLL no matter what you're putting into the runtime library setting. What I think you want to do is change the setting on the DLL's main project page from DLL to Static Library instead of changing the runtime library setting.
Once you've done this, make sure that both the executable and library projects have the same runtime library setting (the /MT switch you refer to), otherwise you'll get tons of strange error messages if the linker is trying to match up two different runtime libraries in the same executable.
|
1,903,954 | 4,609,795 | Is there a standard sign function (signum, sgn) in C/C++? | I want a function that returns -1 for negative numbers and +1 for positive numbers.
http://en.wikipedia.org/wiki/Sign_function
It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere.
Edit: Specifically, I was looking for a function working on floats.
| The type-safe C++ version:
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Benefits:
Actually implements signum (-1, 0, or 1). Implementations here using copysign only return -1 or 1, which is not signum. Also, some implementations here are returning a float (or T) rather than an int, which seems wasteful.
Works for ints, floats, doubles, unsigned shorts, or any custom types constructible from integer 0 and orderable.
Fast! copysign is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellently
Standards-compliant! The bitshift hack is neat, but only works for some bit representations, and doesn't work when you have an unsigned type. It could be provided as a manual specialization when appropriate.
Accurate! Simple comparisons with zero can maintain the machine's internal high-precision representation (e.g. 80 bit on x87), and avoid a premature round to zero.
Caveats:
It's a template so it might take longer to compile in some circumstances.
Apparently some people think use of a new, somewhat esoteric, and very slow standard library function that doesn't even really implement signum is more understandable.
The < 0 part of the check triggers GCC's -Wtype-limits warning when instantiated for an unsigned type. You can avoid this by using some overloads:
template <typename T> inline constexpr
int signum(T x, std::false_type is_signed) {
return T(0) < x;
}
template <typename T> inline constexpr
int signum(T x, std::true_type is_signed) {
return (T(0) < x) - (x < T(0));
}
template <typename T> inline constexpr
int signum(T x) {
return signum(x, std::is_signed<T>());
}
(Which is a good example of the first caveat.)
|
1,904,078 | 1,914,717 | How do I create a WT project in MSVC? | If anyone has used WT successfully with MSVC (mine is 2005), could you please provide some details on how this can be done?
I have installed WT fine , then ran some examples. The problems begin when I try to create a project of my own, as simple as hello.C. I get a thousand compiler errors like this one :
C:\Program Files\Microsoft Visual Studio 8\VC\include\cstdio(25) : error C2143: syntax error : missing '{' before ':'
Possibly some project tuning is required, which I could not figure out, despite trying for many hours...Any help will be appreciated.
[Edit] WT is the Witty (webtoolkit.eu)
| Well after searching and googling around for some days , it seems that using CMake is a must in order to build a WT project. This page explains the procedure. Hopefully it will save you some time.
|
1,904,340 | 1,904,363 | Global Variable Count | How to count the number of global variables in C++ with a program that I can run with Grep?
| A better method is to have your compiler print a map file. Most map files list all the global variables and their locations. If you're lucky, the map file may even indicate which translation unit the global variable belongs to.
|
1,904,592 | 1,904,596 | Building VOIP into an application (C++ specifically) | Are there existing libraries and frameworks which allow VOIP to be built into a bespoke application without reinventing the wheel? A customer is interested by the possibility for a C++ desktop application and while it's not hugely useful (they could just use skype), it is quite cool.
I believe some technologies like DirectX may have some functionality built in for in-game chat, is that right? What else is there in the form of free/paid 3rd-party libraries?
| Well, since Asterisk is open source, that's a good place to start.
Check out Astxx
"The goal of Astxx is to provide a fully functional and easy to use C++
wrapper for Asterisk enabling developers to write Asterisk related software
using the full range of what C++ has to offer. This includes AGI scripts
and accessing the Manager API."
Also IAXClient
"A lightweight cross platform IP telephony client using the IAX protocol, designed for use with the asterisk open source PBX. "
And Asterisk Sockets
"Asterisk Manage API and FAGI C++ Framework. Implemented with high efficient OS independent Sockets wrapper (ACE). Provide C++ API wrappers for Asterisk Manager API and FAGI."
There's also a .NET library
"The Asterisk .NET library consists of a set of C# classes that allow you to easily build applications that interact with an Asterisk PBX Server (1.0/1.2/1.4 version). Both FastAGI and Manager API supported. .NET/Mono compatible."
|
1,904,606 | 1,904,627 | C++ RTTI and Derived Classes | My C++ is a bit rusty. Here's what I'm attempting to do:
class Cmd { };
class CmdA : public Cmd { };
class CmdB : public Cmd { };
...
Cmd *a = new CmdA ();
Cmd *b = new CmdB ();
First problem:
cout << typeid (a).name ()
cout << typeid (b).name ()
both return Cmd * types. My desired result is CmdA* and CmdB*. Any
way of accomplishing this other than:
if (dynamic_cast <CmdA *> (a)) ...
Second, I would like to do something like this:
class Target {
public:
void handleCommand (Cmd *c) { cout << "generic command..." }
void handleCommand (CmdA *a) { cout << "Cmd A"; }
void handleCommand (CmdB *b) { cout << "Cmd B"; }
};
Target t;
t.handleCommand (a);
t.handleCommand (b);
and get the output "Cmd A" and "Cmd B". Right now it prints out
"generic command..." twice.
Thanks
| Ah but typeid(a).name() will be Cmd* because its defined as Cmd*. typeid(*a).name() should return CmdA
http://en.wikipedia.org/wiki/Typeid
Also, the base class of whatever you pass to typeid must have virtual functions, otherwise you get back the base class.
MSDN has a more eloquent explanation for that:
If the expression points to a base
class type, yet the object is actually
of a type derived from that base
class, a type_info reference for the
derived class is the result. The
expression must point to a polymorphic
type (a class with virtual functions).
Otherwise, the result is the type_info
for the static class referred to in
the expression. Further, the pointer
must be dereferenced so that the
object it points to is used. Without
dereferencing the pointer, the result
will be the type_info for the pointer,
not what it points to.
|
1,904,635 | 1,904,659 | warning C4003 and errors C2589 and C2059 on: x = std::numeric_limits<int>::max(); | This line works correctly in a small test program, but in the program for which I want it, I get the following compiler complaints:
#include <limits>
x = std::numeric_limits<int>::max();
c:\...\x.cpp(192) : warning C4003: not enough actual parameters for macro 'max'
c:\...\x.cpp(192) : error C2589: '(' : illegal token on right side of '::'
c:\...\x.cpp(192) : error C2059: syntax error : '::'
I get the same results with:
#include <limits>
using namespace std;
x = numeric_limits<int>::max();
Why is it seeing max as the macro max(a,b); ?
| This commonly occurs when including a Windows header that defines a min or max macro. If you're using Windows headers, put #define NOMINMAX in your code, or build with the equivalent compiler switch (i.e. use /DNOMINMAX for Visual Studio).
Note that building with NOMINMAX disables use of the macro in your entire program. If you need to use the min or max operations, use std::min() or std::max() from the <algorithm> header.
|
1,904,636 | 1,904,648 | Decent tool/library for C++ to handle XML? | I need to do some XML-related job (parsing, comparison etc). Is there any C++ library for this that you know works good ? Preferrably for Win XP. Thanks.
| PugiXml will do it.
|
1,904,760 | 1,904,812 | Tool to create wizards in C++ | The MFC concept (using PropertySheet / PropertyPages) to build a wizard has let me down many times and for several reasons. I googled the subject somewhat but could not turn up with any library or tool that would help me create my wizards easier.
Any recommendations would help a lot.
| Did you look at this article:
http://www.codeguru.com/cpp/w-d/dislog/wizards/article.php/c5083/
LogicNP Software
|
1,904,796 | 1,906,624 | specializing functions on stl style container types | If i have a type T, what is a useful way to inspect it at compile time to see whether its an STL-style container (for an arbitrary value type) or not?
(Assumption: pointers, reference, etc. already stripped)
Starting code:
template<class T> // (1)
void f(T&) {}
template<class T> // (2)
void f(std::vector<T>&) {}
void test()
{
int a;
std::vector<int> b;
f(a);
f(b);
}
Now this works fine, but what if i want to generalize the container (i.e. not define (3), (4), ... explicitly)?
Utilizing SFINAE and typelists would reduce the code somewhat, but is there a better way?
Or is there an idiom for specializing based on concepts?
Or could i somehow utilize SFINAE to selectively enable only the desired specializations?
As a sidenote, i can't use iterators - i am trying to specialize based on functions that receive Ts as parameters.
As per MSalters answer:
template<class T>
void f(T&, ...) {
std::cout << "flat" << std::endl;
}
template<class Cont>
void f(Cont& c, typename Cont::iterator begin = Cont().begin(),
typename Cont::iterator end = Cont().end()) {
std::cout << "container" << std::endl;
}
(The variable argument list is needed to make the first f the least preferred version to solve ambiguity errors)
| STLcontainers by definition have a typedef iterator, with 2 methods begin() and end() retruning them. This range is what the container contains. If there's no such range, it's not a container in the STL sense. So I'd sugegst something along the line of (not checked)
template<typename CONTAINER>
void f(CONTAINER& c,
typename CONTAINER::iterator begin = c.begin(),
typename CONTAINER::iterator end = c.end())
{ }
|
1,904,846 | 1,906,180 | DirectX: How do you initialize the vertex buffer and index buffer for a cone? | How do you initialize the vertex buffer and index buffer for a cone in DirectX 9 in C++?
| Well its fairly easy.
A cone has a single point at one end.
At the other end you have a circle. Obviously the more points you have in that circle the more circular it looks.
You can plot a circle using
x = r * cos( theta );
y = r * sin( theta );
To make any triangle you can do it by plugging theta and theta plus some small epsilon (2Pi / 60 would give you 60 points round the base of the cone). Your final coordinate is the top 1. Bung each set of the 3 indices into an index buffer and you are good to go.
|
1,904,993 | 1,943,845 | Change brightness of blitted bitmap using Allegro | I'm using the Allegro game library to make a tile game. I want the tiles to get exponentially brighter. Unfortunately Allegro does not have a "Brighten" feature. What I then decided to do, was blit a tile to the buffer, then for each pixel that it just blited for that tile, I increased their rgb values and putpixel. The big problem with this is it severely decreased my framerate since it does twice as much work. Is there any way I can achieve this without having a tile bitmap for each tile that is slightly brighter (which would be ridiculous). Thanks
| You can use:
draw_lit_sprite
what it does is take a BITMAP and draw it using a "light" that you have to set before by using this function:
set_trans_blender
so basically, what you have to do is:
//Init allegro code here
init_allegro_stuff();
//It takes as arguments red, green, blue, alpha
//so in this case it's a white light
set_trans_blender(255, 255, 255, 255);
//Draws the sprite like draw_sprite but with intensity
draw_lit_sprite(buffer, yourSprite, x, y, intensity);
hope it helps :)
|
1,905,058 | 1,905,065 | Open Source Executable Editor | I have a native C++ windows app that i would like to edit. Are there any open source tools for me to do this on Windows? I want to edit the executable directly.
| Allow me to direct you toward this Stack Overflow question, the accepted answer of which links to this hex editor comparison chart, including license info.
|
1,905,070 | 1,905,651 | Unit testing an executable project | Maybe I am not thinking about this correctly.
I am starting my second project using unit tests. My first project I rolled my own, for this project I am trying out Boost::test.
My question is, what are the proper procedures for unit testing projects that compile into executables? It seems like everything I see out there is for libraries and dependencies. I want my exe project to be unit tested, but I do not want a bunch of unit test functions floating around in the binary, nor do I want to do
#ifdef _DEBUG
BOOST_AUTO_TEST_CASE( my_func )
{
}
#endif
around all my tests.
I thought about creating a separate project for unit tests, but that does not really work for executable.. unless I want to do some fancy pre-build operation copying from my other project into the test project..
Any thoughts or ideas?
| The project can be compiled as a library and this library linked, possibly statically, in two separate executables: the "project", which will be delivered, and the unit tests.
Now the problem seems to originate from your IDE, which one is it ? Does it allow to create two binaries for one project ?
|
1,905,079 | 1,905,094 | Using exceptions to abort series of user inputs - Good? Bad? | Consider a scenario where a console application asks for a series of inputs, one after the other. Each input is validated before proceeding to the next. Now if an input made by the user is invalid, an error message is shown and the user is asked if he/she wants to continue. If the user chooses no, the input process is aborted. If the user chooses yes, the user is allowed to retype the input again, and the process continues by asking for the remainder of the inputs.
If I used a read() method to handle the user inputs (which also validates the input and asks if the user wishes to continue [y/n]) that returns false if the user chooses not to continue, then I would have to check for the result of every read() call before proceeding to the next
For example:
bool valid = read("Name");
if (valid) valid = read("Age");
if (valid) valid = read("Sex");
if (valid) valid = read("DoB");
if(valid)
{
// do stuff
}
Alternatively, I can have the read() method throw an exception if the user chooses to discontinue, in which case my code would become:
try {
read("Name");
read("Age");
read("Sex");
read("DoB");
// do stuff
}catch(input_exception& e)
{}
Which of these approaches would you choose and why? (Assume that the read() method throws the exception properly after cleaning up)
NOTE: I'm not looking for arguments for and against exceptions, which is abundantly available on SO. I'm only looking for an answer to the specific question.
| I, personally, would do it something like this:
bool valid = read("Name")
&& read("Age")
&& read("Sex")
&& read("DoB");
It's equivalent to the first code you posted. The && operator in C++ evaluates terms left-to-right and stops when a false outcome is encountered. This is not a compiler-specific hack, but well-defined behavior in C, C++, and many many other programming languages based on or inspired by C.
This also works for ||, but it stops when a true value is encountered rather than a false one.
|
1,905,228 | 1,911,785 | Suppress unused variable warning in C++ => Compiler bug or code bug? | Presently, I am using the following function template to suppress unused variable warnings:
template<typename T>
void
unused(T const &) {
/* Do nothing. */
}
However, when porting to cygwin from Linux, I am now getting compiler errors on g++ 3.4.4 (On linux I am 3.4.6, so maybe this is a bug fix?):
Write.cpp: In member function `void* Write::initReadWrite()':
Write.cpp:516: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
../../src/common/Assert.h:27: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
make[1]: *** [ARCH.cygwin/release/Write.o] Error 1
The argument to unused is a member variable declared as:
volatile bool readWriteActivated;
Is this a compiler bug or a bug in my code?
Here is the minimal test case:
template<typename T>
void unused(T const &) { }
int main() {
volatile bool x = false;
unused(!x); // type of "!x" is bool
}
| It is a compiler bug and there are no known work arounds:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=42655
It is fixed in v4.4.
|
1,905,237 | 1,905,248 | Where in memory is vtable stored? | Where in memory is vtable stored?
| Depends on compiler.
In VC++, the vtable pointer stored at the beginning of the object allocation, before any member data. (Provided your class has at least one virtual member function.)
There also may be multiple vtable pointers, if your class multiply-inherits from other classes with vtables.
The vtables themselves are statically allocated somewhere in your address space.
Then the object layout looks like (for an instance of C):
A's VTable ptr
A's member variables.
B's Vtable ptr
B's member variables.
C's member variables.
for the heirarchy
class A {
virtual Ax() {}
int a, b;
};
class B {
virtual Bx() {}
int c, d;
};
class C : public A, public B {
int foo, bar;
};
|
1,905,336 | 1,905,354 | structure on a heap memory | This question was recently asked to me in an interview for which i went confused!!
"How do you initialize a structure in the heap memory ?"
could anybody please tell me the correct answer for this?
btw:how exactly are stack and heap memory are different from each other?
And looking about the above question some might also ask me about how do you initialize a structure on a stack memory?.
may be this is a basic question or might be a wrong question too, but i am just curious to know!
Could anybody please help?
| The stack lives exactly as long as the function instance defining it -- when that function intance returns, that memory's free for recycling (if it's housing a proper C++ object w/destructor and all, that dtor will be called). The heap lives until explicitly freed.
"How do you initialize a struct" (on either kind of memory!-) is a peculiar question -- obviously via its automatically called ctor in C++ (if any), otheriwse with a memcpy or the like -- being in stack or heap makes no difference here.
|
1,905,417 | 1,905,424 | array vs vector vs list | I am maintaining a fixed-length table of 10 entries. Each item is a structure of like 4 fields. There will be insert, update and delete operations, specified by numeric position. I am wondering which is the best data structure to use to maintain this table of information:
array - insert/delete takes linear time due to shifting; update takes constant time; no space is used for pointers; accessing an item using [] is faster.
stl vector - insert/delete takes linear time due to shifting; update takes constant time; no space is used for pointers; accessing an item is slower than an array since it is a call to operator[] and a linked list .
stl list - insert and delete takes linear time since you need to iterate to a specific position before applying the insert/delete; additional space is needed for pointers; accessing an item is slower than an array since it is a linked list linear traversal.
Right now, my choice is to use an array. Is it justifiable? Or did I miss something?
Which is faster: traversing a list, then inserting a node or shifting items in an array to produce an empty position then inserting the item in that position?
What is the best way to measure this performance? Can I just display the timestamp before and after the operations?
| Use STL vector. It provides an equally rich interface as list and removes the pain of managing memory that arrays require.
You will have to try very hard to expose the performance cost of operator[] - it usually gets inlined.
I do not have any number to give you, but I remember reading performance analysis that described how vector<int> was faster than list<int> even for inserts and deletes (under a certain size of course). The truth of the matter is that these processors we use are very fast - and if your vector fits in L2 cache, then it's going to go really really fast. Lists on the other hand have to manage heap objects that will kill your L2.
|
1,905,439 | 1,905,502 | Overload operators as member function or non-member (friend) function? | I am currently creating a utility class that will have overloaded operators in it. What are the pros and cons of either making them member or non-member (friend) functions? Or does it matter at all? Maybe there is a best practice for this?
| Each operator has its own considerations. For example, the << operator (when used for stream output, not bit shifting) gets an ostream as its first parameter, so it can't be a member of your class. If you're implementing the addition operator, you'll probably want to benefit from automatic type conversions on both sides, therefore you'll go with a non-member as well, etc...
As for allowing specialization through inheritance, a common pattern is to implement a non-member operator in terms of a virtual member function (e.g. operator<< calls a virtual function print() on the object being passed).
|
1,905,450 | 1,905,513 | What is the difference between AddressOf in c# and pointer in c++ | I am confused in AddressOf in c# and pointer in c++ ?
Am i right that Addressof is manage execution and pointer is unmanage execution or something else?
| AddressOf is a VB operator, and doesn't exist in C#. It creates a delegate to a procedure. The delegate can be used later to call the procedure in code that does not include the procedure's name.
A pointer in C/C++ is a representation of an address in memory. You can create a pointer to a function and use it to call that function, so in that particular case pointers and delegates behave similarly. However, delegates are not simply function pointers. The most important difference is that delegates can be chained, and call more than one procedure at once.
|
1,905,787 | 1,905,827 | pros and cons of smart pointers | I came to know that smart pointer is used for resource management and supports RAII.
But what are the corner cases in which smart pointer doesn't seem smart and things to be kept in mind while using it ?
| Smart pointers don't help against loops in graph-like structures.
For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak.
Garbage collection could help against that - it could see that both object are unreachable and free them.
|
1,905,876 | 1,905,881 | Which STL container to use if I want it to ignore duplicated elements? | I am looking for some STL (but not boost) container, which after the following operations will contain 2 elements: "abc" and "xyz":
std::XContainer<string> string_XContainer;
string_XContainer.push_back("abc");
string_XContainer.push_back("abc");
string_XContainer.push_back("xyz");
By the way, I need it just in order to call string_XContainer.size() in the end, to get the total number of unique strings. So maybe I don't even need a container, and there is a more elegant way of doing it?
| std::set is the one you are after. A set will contain at most one instance of each element, compared according to some comparator function you define.
This would be one approach to get the number of unique strings. From your example, the strings were already in sorted order? If that's the case, then you could just create an array (or some other simple structure) and use the std::unique algorithm.
|
1,905,951 | 1,906,157 | is there a design pattern that isolate 'methods' from member? | basically, i want to have something like:
class DataProcessor{
};
however, in the future, i will need to pass DataProcessor's instance to some other functions, because DataProcessor contains some crucial data.
what I got in mind is to separate the members from methods:
class DataProcessorCore{};
class DataProcessor : public DataProcessorCore {};
Is this a common way to do this job? or there is some patterns out there that I can fit my ideas into?
thanks a lot
| Maybe the Strategy Pattern is the one you are looking for. This would give you the oppurtunity to change the methods working on your data at runtime.
wiki: strategy pattern
|
1,906,000 | 1,906,168 | C++ by-reference argument and C linkage | I have encountered a working (with XLC8 and MSFT9 compilers) piece of code, containing a C++ file with a function defined with C linkage and a reference argument. This bugs me, as references are C++ only. The function in question is called from C code, where it is declared as taking a pointer argument to the same type in place of the reference argument.
Simplified example:
C++ file:
extern "C" void f(int &i)
{
i++;
}
C file:
void f(int *);
int main()
{
int a = 2;
f(&a);
printf("%d\n", a); /* Prints 3 */
}
Now, the word on the street is that most C++ compilers, under the hood, implement references just like a pointer. Is it like that and just pure luck the reason this code works or does it say somewhere in the C++ specification what the result is when you define a function with a reference argument and C linkage? I haven't been able to find any information on this.
| My copy of n3000.pdf (from here), has this to say in section 7.5—Linkage specifications:
9. Linkage from C++ to objects defined in
other languages and to objects defined
in C++ from other languages is
implementation-defined and
language-dependent. Only where the
object layout strategies of two
language implementations are similar
enough can such linkage be achieved.
Since C and C++ are different languages, this means that you can't rely on this "feature" of common compilers.
Stronger is note 5 in the same section (emphasis mine):
If two declarations declare functions
with the same name and
parameter-type-list (8.3.5) to be
members of the same namespace or
declare objects with the same name to
be members of the same namespace and
the declarations give the names
different language linkages, the
program is ill-formed; no diagnostic
is required if the declarations appear
in different translation units.
So, I would say that what you did is not guaranteed to work according to the standard, and the compiler is not required to print a diagnostic for the example you have given because the declarations are in different translation units.
FYI, it "works for me" with gcc and g++ version 4.2.1 on Snow Leopard.
|
1,906,126 | 1,906,159 | Simple C++ (or c) libraries for things such as fetching URL's | I am needing to write some code that I can compile and run on Windows, OS/X, and iPhone. The iphone is fairly limited in what you can include. Are there any simple libraries or websites that provide source code for basic things that could be compiled and use on the iPhone as well as everything else?
| One of the popular libraries for HTTP access from C is libcurl. A quick search showed that other people have been able to compile cURL at least as a static library for use in iPhone apps.
|
1,906,166 | 1,906,222 | Inter-Process Communication Recommendation | I'm searching for a light-weight, fast and easy way to handle Inter Process Communication between some programs on a Linux machine.
Currently, I'm thinking Named Pipe, because it's provided by the OS itself. Are there any caveats about the performance or usability?
Would Shared Memory be better?
I don't think I need a super-complex Framework.
Please point me in the right direction, thanks!
Update:
I want to build a small program (daemon) that tells other programs (which it itself starts) to pause, report their status back, stop etc.
So the other program should be notified that a new command is waiting for it. A pipe is not ideal for that, is it?
| Boost has a nice InterProcess library that is cross-platform and quite intuitive.
I have only toyed with it though, so there might be better alternatives out there.
However, if you don't really need shared memory, I would stick with a messaging approach. You'll avoid deadlocks and race conditions. The pipe principle is really great, and it even allows for lazy behaviors which may save you a lot of processing depending on the matter at hand!
|
1,906,238 | 1,906,353 | Macro definition for message mapping | Formerly I asked a question and got a fair response. But I am stucked with below macro definitions.
The below definitions generates a Message Map function like it is in MFC Message Map. But the code below does not compile.
Whole statements starting with this-> are problematic ones except the one in MSG_HANDLER this->meth(msg); dont know why..
Hence what can be done to correct this issue?
I use VS 2008.
#define MSG_UNPACK(var, id, msg) x##id *var = (x##id *)(msg);
#define BEGIN_MSG_MAP \
protected: \
virtual void dispatchToMsgMap(xMessage *msg)\
{ \
if (msg->msg.message == WM_NULL) \
{ \
return; \
}
#define MSG_HANDLER(meth, wm_msg) \
else if (msg->msg.message == wm_msg) \
{ \
this->meth(msg); \
return; \
}
#define END_MSG_MAP(base) \
else if (msg->msg.message == WM_COMMAND) \
{ \
this->dispatchToCmdMap(msg); \
return; \
} \
else if (msg->msg.message == WM_NOTIFY) \
{ \
this->dispatchToNotifyMap(msg); \
return; \
} \
\
base::dispatchToMsgMap(msg); \
};
#define BEGIN_CMD_MAP \
virtual void dispatchToCmdMap(xMessage *msg)\
{ \
MSG_UNPACK(Cmd, WM_COMMAND, msg); \
\
if (Cmd->ItemID == 0) \
{ \
/* not allowed */ \
}
#define CMD_HANDLER(meth, cmd_id) \
else if (Cmd->ItemID == cmd_id) \
{ \
this->meth(Cmd->ItemID); \
}
#define END_CMD_MAP(base) \
else \
{ \
base::dispatchToCmdMap(msg); \
} \
};
Here, for example this->dispatchToCmdMap(msg); \ is 41st line.
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(41) : error C2059: syntax error : 'this'
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(41) : error C2017: illegal escape sequence
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(42) : error C2059: syntax error : 'return'
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(42) : error C2017: illegal escape sequence
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(43) : error C2059: syntax error : '}'
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(43) : error C2143: syntax error : missing ';' before '}'
1>d:\devel\coding\vs2008\test2\test2\messagemapper.h(43) : error C2059: syntax error : '}'
| The "illegal escape sequence" part tells me that you have traling whitespace after your \. Therefore the next lines are not part of the macro.
|
1,906,505 | 1,906,527 | C++: #include file search? | This MSDN document quotes:
look for include files in the same
directory of the file that contains
the #include statement, and then in
the directories of any files that
include (#include) that file
Wait, what?
What does that actually mean (the bold stuff)?
| It probably means that if foo/bar/baz.c includes ../bog/bog.h, and the latter contains
#include "fix.h"
it would find foo/bar/fix.h. In other words, it looks in the directory that contained the C file that included the header containing the include. Clear? :)
So, the file layout rendered as gorgeous ASCII graphics, is:
foo/
|
+-bar/
| |
| +-baz.c
| |
| +-fix.h
|
+-bog/
|
+-bog.h
And bog.h is then able to find fix.h in the sibling directory foo.
|
1,906,561 | 1,906,842 | communication between c++ and c# through pipe | I want to send data from a c# application to a c++ application through a pipe.
Here is what I've done:
this is the c++ client:
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[]) {
HANDLE hFile;
BOOL flg;
DWORD dwWrite;
char szPipeUpdate[200];
hFile = CreateFile(L"\\\\.\\pipe\\BvrPipe", GENERIC_WRITE,
0, NULL, OPEN_EXISTING,
0, NULL);
strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe");
if(hFile == INVALID_HANDLE_VALUE)
{
DWORD dw = GetLastError();
printf("CreateFile failed for Named Pipe client\n:" );
}
else
{
flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
if (FALSE == flg)
{
printf("WriteFile failed for Named Pipe client\n");
}
else
{
printf("WriteFile succeeded for Named Pipe client\n");
}
CloseHandle(hFile);
}
return 0;
}
and here the c# server
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace PipeApplication1{
class ProgramPipeTest
{
public void ThreadStartServer()
{
// Create a name pipe
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("\\\\.\\pipe\\BvrPipe"))
{
Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
// Wait for a connection
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");
using (StreamReader sr = new StreamReader(pipeStream))
{
string temp;
// We read a line from the pipe and print it together with the current time
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", DateTime.Now, temp);
}
}
}
Console.WriteLine("Connection lost");
}
static void Main(string[] args)
{
ProgramPipeTest Server = new ProgramPipeTest();
Thread ServerThread = new Thread(Server.ThreadStartServer);
ServerThread.Start();
}
}
}
when I start the server and then the client GetLastErrror from client returns 2 (The system cannot find the file specified.)
Any idea on this.
Thanks
| At a guess, I'd say you don't need the "\.\Pipe\" prefix when creating the pipe in the server. The examples of calling the NamedPipeServerStream constructor that I've seen just pass-in the pipe name. E.g.
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("BvrPipe"))
You can list the open pipes, and their names, using SysInternals process explorer. This should help you verify that the pipe has the correct name. See this question for details.
|
1,906,565 | 1,906,804 | PHP extension library accessing PHP superglobals | I have written a PHP extension library in C++. I am writing the extension for PHP 5.x ad above.
I need to access PHP superglobals in my C++ code. Does anyone know how to do this?. A code snippet or pointer (no pun inteded) to a similar resource (no pun ...) would be greatly appreciated.
| What data do you actually need? - Best way for most data is to refer to the C structure they are coming from. For instance with request data you can check the sapi_globals, accessible using the SG() macro, session data is available via the session module, ...
If you really need access to a super global you can find it in the EG(symbol_table) hash table. As PHP has a JIT mechanism to provide super globals only when needed you might need to call zend_auto_global_disable_jit() first to disable this.
Answering the comment below: Is any of this data enough:
typedef struct {
const char *request_method;
char *query_string;
char *post_data, *raw_post_data;
char *cookie_data;
long content_length;
uint post_data_length, raw_post_data_length;
char *path_translated;
char *request_uri;
const char *content_type;
zend_bool headers_only;
zend_bool no_headers;
zend_bool headers_read;
sapi_post_entry *post_entry;
char *content_type_dup;
/* for HTTP authentication */
char *auth_user;
char *auth_password;
char *auth_digest;
/* this is necessary for the CGI SAPI module */
char *argv0;
/* this is necessary for Safe Mode */
char *current_user;
int current_user_length;
/* this is necessary for CLI module */
int argc;
char **argv;
int proto_num;
} sapi_request_info;
typedef struct _sapi_globals_struct {
void *server_context;
sapi_request_info request_info;
sapi_headers_struct sapi_headers;
int read_post_bytes;
unsigned char headers_sent;
struct stat global_stat;
char *default_mimetype;
char *default_charset;
HashTable *rfc1867_uploaded_files;
long post_max_size;
int options;
zend_bool sapi_started;
time_t global_request_time;
HashTable known_post_content_types;
} sapi_globals_struct;
Then use SG(request_info).request_urior similar, while you should only read these values, not write, so make a copy if needed.
None of these is enough? - Then go back to what I said above:
/* untested code, might need some error checking and stuff */
zval **server_pp;
zval **value_pp;
zend_auto_global_disable_jit("_SERVER", sizeof("_SERVER")-1 TSRMLS_CC);
if (zend_hash_find(EG(symbol_table), "_SERVER", sizeof("_SERVER"), (void**)&server_pp) == FAILURE) {
zend_bailout(); /* worst way to handle errors */
}
if (Z_TYPE_PP(server_pp) != IS_ARRAY) {
zend_bailout();
}
if (zend_hash_find(Z_ARRVAL_PP(server_pp), "YOUR_VARNAME", sizeof("YOUR_VARNAME"), (void**)&value_pp) == FAILURE) {
zend_bailout();
}
/* now do something with value_pp */
Please mind that I jsut typed it here out of my ind without checking anything so it can be wrong, contain typos etc.
And as a note: You should be aware of the fact that you have to use sizeof() not sizeof()-1 with hash APIs as the terminating null-byte is part of the calculated hash and has functions return SUCCESS or FAILURE, while SUCCESS is defined as 0 and FAILURE as -1 which is not what one might expect, so always use these constants!
|
1,906,605 | 1,918,944 | ntdll!kifastsystemcallret | My program is crashing at the end of execution, and couldnt even see stack unwind info.
all i can see is this " ntdll!kifastsystemcallret", can some throw some light?
| KiFastSystemCallRet means that the thread is in a syscall - an unfortunate aspect of x86 NT syscall dispatch is that it will not return the context back to the original place, but has to return to a static location in ntdll, which will fix up the context and put you back where you came from. Paste in the stacks and we can give you some more hints...
|
1,906,691 | 1,906,942 | How to prevent a file from being tampered with | I want to store confidential data in a digitally signed file, so that I know when its contents have been tampered with.
My initial thought is that the data will be stored in NVPs (name value pairs), with some kind of CRC or other checksum to verify the contents.
I am thinking of implementing the creating (i.e. writing) and verification (reading) of such a file, using ANSI C++.
Assuming this is the data I want to store:
//Unencrypted, raw data to be stored in file
struct PrivateInfo {
double age; weight;
FitnessScale fitness;
Location loc;
OtherStuff stuff;
};
//128-bit Encrypted Data (Payload to be stored in file)
struct EncryptedData {
// unknown fields/format ??
};
[After I have read a few responses to this question]
Judging by the comments I have received so far, I fear people are getting side tracked by the word "licensing" which seems to be a red flag to most people. I suspected that may be the case, but in todays atmosphere of heightened security and general nervousness, I thought I'd better detail what I needed to be "hiding" lest someone thought I was thinking of passing on the "Nuke password" to some terrorists or something. I will now remove the word "license" from my question.
View it more as a technical question. Imagine I am a student (which I am), and that I am trying to find out about recommended (or best practices) for encoding information that needs to be secure.
Mindful of the above, I will reformat my questions thus:
Given a struct of different data type fields, what is the "recommended" algorithm to give it a "reasonable secure" encryption (I still prefer to use 128 bit - but thats just me)
What is a recommended way of providing a ROBUST check on the encrypted data, so I can use that check value to know if the contents of the file (the Payload of encrypted data) differs from the original.?
| First, note that "signing" data (to notice when it has been tampered with) is a completely separate and independent operation from "encrypting" data (to prevent other people from reading it).
That said, the OpenPGP standard does both. GnuPG is a popular implementation: http://www.gnupg.org/gph/en/manual.html
Basically you need to:
Generate a keypair, but don't bother publishing the public part.
Sign and encrypt your data (this is a single operation in gpg)
... storage ...
Decrypt and check the signature (this is also a single operation).
But, beware that this is only any use if you can store your private key more securely than you store the rest of the data. If you can't guarantee the security of the key, then GPG can't help you against a malicious attempt to read or tamper with your data. And neither can any other encryption/signing scheme.
Forgetting encryption, you might think that you can sign the data on some secure server using the private key, then validate it on some user's machine using the public key. This is fine as far as it goes, but if the user is malicious and clever, then they can invent new data, sign it using their own private key, and modify your code to replace your public key with theirs. Their data will then validate. So you still need the storage of the public key to be tamper-proof, according to your threat-model.
You can implement an equivalent yourself, something along the lines of:
Choose a longish string of random characters. This is your key.
Concatenate your data with the key. Hash this with a secure hash function (SHA-256). Then concatenate the resulting hash with your data, and encrypt it using the key and a secure symmetric cipher (AES).
... storage ...
Decrypt the data, chop off the hash value, put back the key, hash it, and compare the result to the hash value to verify that it has not been modified.
This will likely be faster and use less code in total than gpg: for starters, PGP is public key cryptography, and that's more than you require here. But rolling your own means you have to do some work, and write some of the code, and check that the protocol I've just described doesn't have some stupid error in it. For example, it has potential weaknesses if the data is not of fixed length, which HMAC solves.
Good security avoids doing work that some other, smarter person has done for you. This is the virtuous kind of laziness.
|
1,906,784 | 1,906,827 | PHP extension that uses memcached | I am thinking of writing a PHP extension library that will use the memcached library. It is trivial to simply link my library to the memcache shlib.
However, I am not sure what will happen if my (extension library) user already uses memcache on his/her website. My questions are:
Is it possible to have (possibly different versions) of memcache on the machine?
Is it best to statically link or dynamically link to memcache when building the extension library? (to cater for version incompatibilities - assuming memcache is backward compatible, otherwise all bets are off)
The questions basically degenerate to how may one safeguard an extension library they have written if it has a dependence on a third party file which may already be being used on the website that the extension library is going to be used on?
The question may probably be slightly ill-posed, but I hope you understand the gist of what I am asking.
| Mind that there are two memcache extensions for PHP, one is called memcache, the other memcached, the first uses it's own implementation of the memcache protocol, the later uses the library.
If you're using the first you shouldn't have a conflcit but have to take care of memcache on your own. I'd suggest building an extension which depends on the memcached and re uses the library it found.
|
1,907,012 | 1,908,140 | Which STL containers require the use of CAdapt? | The CAdapt class is provided by Microsoft in order to enable using classes that override the address of operator (operator&) in STL containers. MSDN has this to say about the use of CAdapt:
Typically, you will use CAdapt when you want to store CComBSTR, CComPtr, CComQIPtr, or _com_ptr_t objects in an STL container such as a list.
On to my quesiton:
What is the full list of STL containers with which CAdapt should be used?
If the container contains a key/value pair (such as map) please specify whether CAdapt is needed for the key or the value.
|
What is the full list of STL containers with which CAdapt should be used?
None. Implementations should assume operator& is overloaded, and use the correct expression &reinterpret_cast<char&>(obj)
Now, there is another question that you didn't ask:
My VC++ STL implementation doesn't agree. It does provide CAdapt as a workaround. What is the full list of its containers with which CAdapt should be used?
Top of my head, I'd day vector<T> (stores them as a T[] so reasonably needs arithmetic on them) and deque (stores them as multiple smaller T[]s so same rationale). list, map, set, multiset and multimap all work on nodes, so they themselves already wrap each object.
|
1,907,069 | 1,907,156 | Confused about CWnd::OnLButtonDown() and CTreeCtrl::OnLButtonDown() | MFC Library Reference
CWnd::OnLButtonDown
void CMyCla::OnLButtonDown(UINT nFlags, CPoint point)
{
CWnd::OnLButtonDown(nFlags, point);
}
void CMyTreeCla::OnLButtonDown(UINT nFlags, CPoint point)
{
CTreeCtrl::OnLButtonDown(nFlags, point);
}
I know the inheritance.
class CTreeCtrl : public CWnd
{
......
}
Is there any clear rule to follow when i want to call OnLButtonDown()?
Thank you.
| I think this is what you want.
In your class header, you will need to declare the message map, and also write the function header.
Class myCWnd : public CWnd
{
DECLARE_MESSAGE_MAP() //note, no semi colon
afx_msg void OnLButtonDown( UINT nFlags, CPoint pt );
};
in the cpp file:
BEGIN_MESSAGE_MAP(myCWnd, CWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
void myCWnd::OnLButtonDown( UINT nFlags, CPoint pt )
{
//do what you want here
CWnd::OnLButtonDown(nFlags, pt); //call base class method
}
|
1,907,175 | 1,907,206 | References on statemachine optimization and code generation? | As a follow-up to my state machines as a C++-like language extension question, I'd like some more help.
My compiler has been extended to parse my state machine extensions and now I'm beginning semantic analysis and code generation. There is a description on this page.
Can anyone point me to good references on state machine optimization and code generation?
Edit:
I still haven't found any specific references, but this is an interesting project that I didn't know about: http://echarts.org/
They are doing, in a Java syntax, something very similar to what I'm trying to do. Apparently this project originated at AT&T: http://www.research.att.com/software_tools
| Theres a good chapter or two on state machines in Allen Hollub's book "Compiler Design In C", which also includes lots of (C I'm afraid) code. The book is about writing compiler-compiler type tools, so must cover generation, though it's a few years since I've read it.
|
1,907,214 | 1,907,353 | Why are "inlined" static consts not allowed, except ints? |
Possible Duplicate
Why can't I have a non-integral static const member in a class?
struct Example
{
static const int One = 1000; // Legal
static const short Two = 2000; // Illegal
static const float Three = 2000.0f; // Illegal
static const double Four = 3000.0; // Illegal
static const string Five = "Hello"; // Illegal
};
Is there any reason for which #2, #3, #4 and #5 are illegal?
I think I know the reason for #5: the compiler needs a "real" string object (since it's not a built in type) and cannot mindlessy replace Five with "Hello" as if it was #define Five "Hello". But if that's the case, can't the compiler leave an hint in the .obj files and tell the linker to automatically create one instance of string Five somewhere?
For #3 and #4 and especially #2 (lol!)... I can't really see any possible reason! Floats and doubles are built-in types, just as int is! And short is just a (possibly) shorter integer.
EDIT: I'm using Visual Studio 2008 to compile it. I thought all compilers behaved the same in this case, but apparently g++ compiles that fine (except #5). The errors VS gives for that snippets are:
error C2864: 'Example::Two' : only static const integral data members can be initialized within a class
error C2864: 'Example::Three' : only static const integral data members can be initialized within a class
error C2864: 'Example::Four' : only static const integral data members can be initialized within a class
error C2864: 'Example::Five' : only static const integral data members can be initialized within a class
| The int and the short are legal, and if your compiler doesn't allow them then your compiler is bust:
9.4.2/4: ... If the static data member is of const integral or const
enumeration type, its declaration in
the class definition can specify a
constant-initializer which shall be an integral constant expression.
I believe that the reason that floats and doubles aren't treated specially as constants in the C++ standard, in the way that integral types are, is that the C++ standard is wary that the arithmetic operations on float and double could be subtly different on the compiling machine, than they are on the machine that executes the code. For the compiler to evaluate a constant expression like (a + b), it needs to get the same answer that the runtime would get.
This isn't so much of an issue with ints - you can emulate integer arithmetic relatively cheaply if it differs. But for the compiler to emulate floating-point hardware on the target device might be very difficult. It might even be impossible, if there are different versions of the chip and the compiler doesn't know which the code will run on. And that's even before you start messing with the IEEE rounding mode. So the standard avoided requiring it, so that it didn't have to define when and how compile-time evaluation can differ from runtime evaluation.
As Brian mentions, C++0x is going to address this with constexpr. If I'm right about the original motivation, then presumably 10 years has been long enough to work through the difficulties in specifying this stuff.
|
1,907,668 | 1,907,739 | What do I need to know about memory in C++? | I've been doing my best to learn C++ but my previous training will fall short in one major issue: memory management. My primary languages all have automatic garbage collection, so keeping track of everything has never really been necessary. I've tried reading up on memory management in C++ online, but I have this shaking suspicion that I am strill missing something.
So, here's a multi-part question:
What is the bare minimum I need to know about memory management? (or, where do I go to find that out)?Where do I go for intermediate and advanced knowledge/tutorials/etc (once I am done with the basics)?More specifically:What is the performance difference between pointers and references?I've heard that in loops, you need to make sure that you call delete on any new pointers before the loop re-iterates. Is this correct? Do you need to do something with references?What are some classic examples of memory leaks?What do I need to know about the following (and will I ever realistically need to use them -- if so, where?):
mallocfreecallocrealloc
*********************** UPDATE *******************
This is to address a reference to lmgtfy in comment one (by Ewan). If you start reading the information which is available there, it is not useful to the beginner. It is great theory, I think, but it is neither pertinent or useful to this question.
| You really, really need to read a good book - learning C++ frankly is not possible without one. I recommend Accelerated C++, by Koenig & Moo, two of the originators of C++.
|
1,907,795 | 1,907,822 | What is going on at the top of this function | I'm currently looking at a function example that I can't seem to figure out using MFC in Visual C++. The function is as follows
CMFC_OSG_MDIView::CMFC_OSG_MDIView() :mOSG(0L)
{
}
I understand everything here except the mOSG(0L) snippet. mOSG was declared in the MFC_OSG _MDIView class as follows:
cOSG* mOSG;
| CMFC_OSG_MDIView::CMFC_OSG_MDIView() :mOSG(0L)
{
}
The above is a constructor, for a class called CMFC_OSG_MDIView. :mOSG(0L) is called initializer list, which is executed when an object is created. The init-list gets called before the body of the constructor, and it is the correct place to initialize the member variables.
|
1,907,921 | 1,907,953 | Can using 0L to initialize a pointer in C++ cause problems? | In this question an initializer is used to set a pointer to null. Instead of using value of 0 value of 0L is used. I've read that one should use exactly 0 for null pointers because exact null pointer representation is implementation-specific.
Can using 0L to set a pointer to null cause problems while porting?
| From the standard (4.10.1):
A null pointer constant is an integral
constant expression (5.19) rvalue of
integer type that evaluates to zero
so I guess 0L is ok.
|
1,908,269 | 1,908,651 | Best way to add python scripting into QT application? | I have a QT 4.6 application (C++ language) and i need to add python scripting to it on windows platform. Unfortunately, i never embed python before, and it seems to be a lot of different ways to do so. Can anyone share his wisdom and point me into some articles/documentation i can read to perform a specified task in less painful way?
| Edit:
You can use PythonQt (not PyQt) that allow you to use Python with Qt. I think this is what you are searching for.
Here a documentation on the official website: http://doc.qt.digia.com/qq/qq23-pythonqt.html.
|
1,908,341 | 1,908,551 | Is C++ the single language that have both pointers and references? | Amongst the programming languages I know and those I've been exposed to, C++ looks like the only one to have both pointers and references. Is it true?
| Algol 68 and Pascal certainly do. IIRC, Ada does too, though I don't remember all the details. PL/I did as well -- it may (easily) have been the first to include both.
Algol 68's references were really more like C++ pointers though. In C++, once you initialize a reference, it always refers to the same object. In Algol 68, you could "reseat" a reference, so it referred to a different object.
It's been a while since I used Pascal, but if memory serves its only use of references is for parameter passing (i.e. a var parameter passes by reference). I don't think you can create a reference other than as a parameter.
Ada allows you to mark parameters as in, out, or inout. If I recall correctly, some inout parameters are copied into the function, then copied back to the caller at the end, but others are pass by reference. As I said, I don't remember the details though.
|
1,908,512 | 1,908,536 | C++ - Hold the console window open? | My question is super simple, but I'm transitioning from C# to C++, and I was wondering what command holds the console window open in C++?
I know in C#, the most basic way is:
Console.ReadLine();
Or if you want to let the user press any key, its:
Console.ReadKey(true);
How do you do this in C++? The only reason I ask this simple of a question here, is that I haven't been able to find a good and clear answer out there on the internet.
| How about std::cin.get(); ?
Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main().
|
1,908,634 | 1,908,694 | CSocket doesn't receive OnClose or OnReceive when you disable network connection on the client side | I've created a client server application with c++ CSocket. when I connect the client to the server and after that I close the client with normal X button or end task it with taskmanager , server CSocket receives the OnClose event. The problem is when I disable the internet connection on windows that the client is running on, server CSocket doesn't receive the OnClose nor OnReceive event!
Is anyone possibly know what's going on?
Update: I've just tested and saw that client didn't recieve the OnClose too! I disabled the internet connection on the windows that the client is running on!
| The client side is shutdown without being able to close the connection to the server via a FIN or RST. For the server to detect that the client is dead it must either have data to send (which would fail) or must send periodic TCP keepalive probes. TCP_KEEPALIVE can be set as a socket option.
|
1,909,036 | 1,909,066 | Support for C++ refactoring in VS (auto-updating references and header/cpp) | In Visual C# I can rename an entity at its definition, and with two clicks all references to that entity get updated. How do I do this in Visual C++? If it's not supported, is there another IDE that supports it?
Note that in the C++ case I also want automatic header/implementation synchronization, so I hardly ever need to do duplicate work.
| VS won't do it alone, but with an add-in like Visual Assist X (Whole Tomato Software) it does quite nicely.
|
1,909,092 | 1,910,052 | QT4: Transparent Window with rounded corners | How can I create a partially transparent window with rounded borders (no standard borders)?
(I used Qt::FramelessWindowHint to disable standard borders)
I tried stylesheets, but border-radius and opacity doesn't seem to have any effect on the window, it only works on children of the enclosing widget.
My second idea was to make the window fully transparent (with setWindowOpacity), and then add an additional widget with rounded corners (since border-radius works on the children), and then group all my other widgets into that widget. But that does not work since setWindowOpacity affects all children as well (I haven't found a way to change this behaviour).
And any ways to make the outer window transparent I could think of (like stylesheets opacity) don't work properly (I only get a black box instead of a transparent window)
Any help would be highly appreciated.
| I had a similar problem where I wanted to paint on a toplevel widget and have only the painted part appear. setWindowOpacity changed the opacity of the painted part, which I didn't want.
this->setAttribute(Qt::WA_TranslucentBackground, true);
changed the opacity of the widget without the painted part. I just tried tossing on a button, and that also displays perfectly opaque. So you should be able to display other children however you like.
|
1,909,127 | 1,909,164 | How to bind c++ dll to my C# program - winCE | i need to bind C++ dll to my C# WinCE program. (scanner dll)
how i can do it ?
thank's in advance
| You need to use Interop to call into unmanaged code.
using System.Runtime.InteropServices; // DllImport
public class Win32 {
[DllImport("User32.Dll")]
public static extern void SetWindowText(int h, String s);
}
Here is an article that discusses the topic in detail (also where the code is sourced from).
http://msdn.microsoft.com/en-us/magazine/cc301501.aspx
|
1,909,136 | 1,909,144 | How to get rid of this Constructor error? | I've taken 2 OOP C# classes, but now our professor is switching over to c++. So, to get used to c++, I wrote this very simple program, but I keep getting this error:
error C2533: 'Counter::{ctor}' : constructors not allowed a return type
I'm confused, because I believe I have coded my default constructor right.
Here's my code for the simple counter class:
class Counter
{
private:
int count;
bool isCounted;
public:
Counter();
bool IsCountable();
void IncrementCount();
void DecrementCount();
int GetCount();
}
Counter::Counter()
{
count = 0;
isCounted = false;
}
bool Counter::IsCountable()
{
if (count == 0)
return false;
else
return true;
}
void Counter::IncrementCount()
{
count++;
isCounted = true;
}
void Counter::DecrementCount()
{
count--;
isCounted = true;
}
int Counter::GetCount()
{
return count;
}
What am I doing wrong? I'm not specifying a return type. Or am I somehow?
| You forgot the semi-colon at the end of your class definition. Without the semi-colon, the compiler thinks the class you just defined is the return type for the constructor following it in the source file. This is a common C++ error to make, memorize the solution, you'll need it again.
class Counter
{
private:
int count;
bool isCounted;
public:
Counter();
bool IsCountable();
void IncrementCount();
void DecrementCount();
int GetCount();
};
|
1,909,608 | 1,909,638 | Why MS Visual Studio 2008 has 2 copies of <sstream> STL file? | This and this.
"c:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\sstream"
"c:\Program Files\Microsoft Visual Studio 9.0\VC\include\sstream"
And the files have small differences. Why 2 files ? Thank you.
| I don't know why the files are different, but the one in the src directory is part of the runtime library source, and shouldn't be used by users of the library. The other file is the one included when you do #include <sstream>.
|
1,909,644 | 1,911,906 | Vista/Win7 Bass and treble volume | I'm having a hard time with this crazy Vista/Win 7 architecture, it might be just me but its hard to get used to it :|
So, my current problem is that I cant set the bass and treble values for my sound card, I found that there is a IAudioBass and IAudioTreble interfaces which can do this, but I'm getting lost how to create these interfaces, I know that I can use the IPart interface to activate them, but it doesnt work, and I guess I'm doing something wrong.
I started to do this in Delphi, but the header conversion took too much time and I just switched to Visual C++ to do it.
Does anyone have some demo source code ?
Thanks a lot for your attention folks !
| You want to start with the IMMDeviceEnumerator API which allows you to discover which of the endpoints on your sound card you want to modify.
You then activate an IDeviceTopology interface. You can walk the IDeviceTopology enumerating parts and activate the IAudioBass and IAudioTreble interfaces off of those parts.
The MSDN documentation for IDeviceTopology contains some sample code which does almost exactly what you're asking for.
I do want to warn you that relatively few current audio solutions have bass and treble controls these days.
|
1,909,734 | 1,912,511 | boosts buffer into char* (no std::string) | So, it may be sounds as a realy newbies question... And proboly it is newbies :)
I try to turn infomation from boost::asio::streambuf which I got, using read_until into char*. I've found realy many examples of turning it into std::string, but I'd mad, if use bufer -> std::string -> c_str in an application, needs a high perfomanse. (But in fact, I ectally do not realy stuff like conteiners and so on.)
| You are assuming that converting a std::string into a C string hurts performance.
This should not be assumed. std::string is often implemented as a wrapper around a C string.
If you are unhappy with current performance, start by using a run-time profiler on your code.
|
1,909,853 | 1,910,024 | Does the caller need to Release the IShellBrowser* obtained via the undocumented WM_GETISHELLBROWSER (WM_USER+7) message? | Several have pointed out that there exists an undocumented message that retrieves the IShellBrowser interface pointer from the common dialog HWND for the file open & save dialogs.
But there is conflicting information (or no information) on whether that pointer is AddRef'd, or if it is just the raw address returned, and no Release() should be called on it?
| No. You might find the following link useful: The Rules of the Component Object Model .
Excerpt:
Reference-Counting Rules
Rule 1: AddRef must be called for
every new copy of an interface
pointer, and Release called for every
destruction of an interface pointer,
except where subsequent rules
explicitly permit otherwise.
The following rules call out common
nonexceptions to Rule 1.
Rule 1a: In-out-parameters to functions. The caller must AddRef the actual parameter, since it will be Released by the callee when the out-value is stored on top of it.
Rule 1b: Fetching a global variable. The local copy of the interface pointer fetched from an existing copy of the pointer in a global variable must be independently reference counted, because called functions might destroy the copy in the global while the local copy is still alive.
Rule 1c: New pointers synthesized out of "thin air." A function that synthesizes an interface pointer using special internal knowledge, rather than obtaining it from some other source, must do an initial AddRef on the newly synthesized pointer. Important examples of such routines include instance creation routines, implementations of IUnknown::QueryInterface, and so on.
Rule 1d: Returning a copy of an internally stored pointer. After the pointer has been returned, the callee has no idea how its lifetime relates to that of the internally stored copy of the pointer. Thus, the callee must call AddRef on the pointer copy before returning it.
Rule 2: Special knowledge on the part
of a piece of code of the
relationships of the beginnings and
the endings of the lifetimes of two or
more copies of an interface pointer
can allow AddRef/Release pairs to be
omitted.
From a COM client's perspective, reference-counting is always a per-interface concept. Clients should never assume that an object uses the same reference count for all interfaces.
The return values of AddRef and Release should not be relied upon, and should be used only for debugging purposes.
Pointer stability; see details in the OLE Help file under "Reference-Counting Rules," subsection "Stabilizing the this Pointer and Keeping it Valid."
See the excellent "Managing Object
Lifetimes in OLE" technical article by
Douglas Hodges, and Chapter 3 of
Inside OLE, 2nd edition, by Kraig
Brockschmidt (MSDN Library, Books) for
more information on
reference-counting.
|
1,909,945 | 1,909,977 | Force derived class to call base function | If I derive a class from another one and overwrite a function, I can call the base function by calling Base::myFunction() inside the implementation of myFunc in the derived class.
However- is there a way to define in my Base class that the base function is called in any case, also without having it called explicitly in the overwritten function? (either before or after the derived function executed)
Or even better, if I have a virtual function in my virtual Base class, and two implemented private functions before() and after(), is it possible to define in the Base class that before and after the function in any derived class of this Base class is called, before() and after() will be called?
Thanks!
| No, this is not possible.
But you can simulate it by calling a different virtual function like so:
class Base
{
public:
void myFunc()
{
before();
doMyFunc();
after();
}
virtual void doMyFunc() = 0;
};
|
1,910,121 | 1,910,180 | Which Design Pattern / RTTI | I'm looking for the best way to dispatch objects to the correct "target" object.
I have a base command class: Cmd, two sub-classes: BufferCmd and StateCmd. Command "GotoLine" is derived from BufferCmd and "ChangeCmd" is derived from StateCmd. BufferCmds are intended to go to a Buffer class and StateCmds are intended to go to a State object.
I currently have a Visitor pattern set up so that I can do something like:
Buffer buffer;
State state;
Cmd *c;
GotoLineCmd gotoCmd = new GotoLineCmd (15);
ChangeCmd changeCmd = new ChangeCommand (...)
c = &gotoCmd;
c->accept (buffer);
c = &changeCmd;
c->accept (state);
I want to use the Visitor pattern because I'd like to be able to do something roughly like:
Cmd *cmds [5];
cmds [0] = new GotoLineCmd (...);
cmds [1] = new CopyLineCmd (...);
cmds [2] = new PasteCmd (...);
foreach (Cmd *c in cmds) {
c->accept (buffer);
}
Unfortunately in order to use this I need do know what object to send the command to. I'd like to be able to do something like this:
Derive Buffer from Commandable
Derive State from Commandable
Commandables *commandables [1] = {new Buffer (), new State () };
// Then have the foreach type statement look like:
foreach (Cmd *c in cmds) {
c->accept (commandables);
}
Is there a pattern that is most appropriate for this type of situation? Should I even be using the Visitor pattern? Obvious I want to avoid this:
foreach (Cmd *c in cmds) {
foreach (Commandable *cmdAbles in commandables) {
if (c->accept (commandables)) {
// Okay command accepted...
break;
}
}
}
Thanks
| Sounds more like you want the aptly-named Command pattern.
The key is to move the differing parameters of accept() into the constructor of each class derived from Cmd. For example, GotoLineCommand's constructor would take the line and the buffer objects as parameters to its constructor, and it would store a pointer or reference to the buffer object.
Once you've done that, you no longer need the parameters to accept() and the interface is the same across all classes derived from Cmd
class Buffer
{
public:
void gotoLine(int line);
};
class Cmd
{
public:
virtual void accept() = 0;
};
class GotoLineCommand: public Cmd
{
public:
GotoLineCommand(Buffer & buffer, int line) :
buffer_(buffer),
line_(line)
{
}
virtual void accept()
{
buffer_.gotoLine(line_);
}
private:
Buffer & buffer_;
int line_;
};
|
1,910,153 | 1,910,227 | _popen: do not show the shell window (SW_HIDE) | When I execute the _popen command in c++ mfc it opens a shell window which I don't like, is it possible to make it hidden? for example when you try to execute commands with ShellExecute function it has the option to hide the shell window with SW_HIDE.
| Note from documentation:
If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirected Input and Output in the Platform SDK.
|
1,910,426 | 1,910,436 | C++ Eclipse Galileo getting it to display line numbers - how? | EDIT: jldupont's suggestion (see below) did the trick
Window -> Preferences -> General -> Editors -> Text Editors -> Show line numbers
I just installed Eclipse Galileo (first time) and am programing in C++ and couldn't get the editor to display the line numbers... When i Googled it I got these directions:
Go to Window -> Preferences -> Editor -> Appearance and check Show line numbers
But when I follow those directions - there is no "Show Line Numbers" check box?
where can i get this 'plug-in' of enable this feature? or does Eclipse have line numbers?
note: i have CDT installed
|
Window -> Preferences -> General -> Editors -> Text Editors -> Show line numbers
|
1,910,712 | 1,910,767 | Dereference vector pointer to access element | If i have in C++ a pointer to a vector:
vector<int>* vecPtr;
And i'd like to access an element of the vector, then i can do this by dereferncing the vector:
int a = (*vecPtr)[i];
but will this dereferencing actually create a copy of my vector on the stack? let's say the vector stores 10000 ints, will by dereferencing the vecPtr 10000 ints be copied?
Thanks!
| 10000 ints will not be copied. Dereferencing is very cheap.
To make it clear you can rewrite
int a = (*vecPtr)[i];
as
vector<int>& vecRef = *vecPtr; // vector is not copied here
int a = vecRef[i];
In addition, if you are afraid that the whole data stored in vector will be located on the stack and you use vector<int>* instead of vector<int> to avoid this: this is not the case.
Actually only a fixed amount of memory is used on the stack (about 16-20 bytes depending on the implementation), independently of the number of elements stored in the vector.
The vector itself allocates memory and stores elements on the heap.
|
1,910,733 | 1,910,834 | how can I map an int to a corresponding string in C/C++ | I have 20 digits and I would like to associate them with strings. Is there a faster way besides using a switch case statement to achieve this.
I need to convert an int to a corresponding string and the numbers aren't necessarily packed. Some code in Qt as well might be useful?
Example: The following digits and strings are associated with each other,
1: "Request System Info"
2: "Change System Info"
10: "Unkown Error"
| easier way to use map
std::map<int, std::string> mymap;
mymap[1] = "foo";
mymap[10] = "bar";
// ...
int idx = 10;
std::string lookup = mymap[idx];
|
1,910,832 | 1,910,992 | Why aren't pointers initialized with NULL by default? | Can someone please explain why pointers aren't initialized to NULL?
Example:
void test(){
char *buf;
if (!buf)
// whatever
}
The program wouldn't step inside the if because buf is not null.
I would like to know why, in what case do we need a variable with trash on, specially pointers addressing the trash on the memory?
| We all realize that pointer (and other POD types) should be initialized.
The question then becomes 'who should initialize them'.
Well there are basically two methods:
The compiler initializes them.
The developer initializes them.
Let us assume that the compiler initialized any variable not explicitly initialized by the developer. Then we run into situations where initializing the variable was non trivial and the reason the developer did not do it at the declaration point was he/she needed to perform some operation and then assign.
So now we have the situation that the compiler has added an extra instruction to the code that initializes the variable to NULL then later the developer code is added to do the correct initialization. Or under other conditions the variable is potentially never used. A lot of C++ developers would scream foul under both conditions at the cost of that extra instruction.
It's not just about time. But also space. There are a lot of environments where both resources are at a premium and the developers do not want to give up either.
BUT: You can simulate the effect of forcing initialization. Most compilers will warn you about uninitialized variables. So I always turn my warning level to the highest level possible. Then tell the compiler to treat all warnings as errors. Under these conditions most compilers will then generate an error for variables that are un-initialized but used and thus will prevent code from being generated.
|
1,911,018 | 1,911,279 | what does std::endl represent exactly on each platform? | Thinking about UNIX, Windows and Mac and an output stream (both binary and text),
What does std::endl represent, i.e. <CR><LF>, <LF> or <CR>? Or is it always the same no matter what platform/compiler?
The reason I'm asking is that I'm writing a TCP client that talks a protocol that expects each command to end in <CR><LF>. So I'm wondering whether to use std::endl or "\r\n" in my streams.
EDIT: Ok, so one flushes the buffer and another doesn't. I get that. But if I'm outputting text to a file, is '\n' equal to <LF> or does it convert to <CR><LF> on Windows and <LF> on Unix or not? I don't see a clear answer yet.
| The code:
stream << std::endl;
// Is equivalent to:
stream << "\n" << std::flush;
So the question is what is "\n" mapped too.
On normal streams nothing happens. But for file streams (in text mode) then the "\n" gets mapped to the platfrom end of line sequence. Note: The read converts the platform end of line sequence back to a '\n' when it reads from a file in text mode.
So if you are using a normal stream nothing happens. If you are using a file stream, just make sure it is opened in binary mode so that no conversion is applied:
stream << "\r\n"; // <CR><LF>
|
1,911,075 | 1,911,082 | G++ not finding <iostream.h> in Ubuntu | I just installed Ubuntu and tried making the famed "Hello World" program to make sure that all the basics were working. For some reason though, g++ fails to compile my program with the error: "'cout' is not a member of 'std'". I've installed the build-essential package. Am I missing something else?
#include <iostream.h>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
Looks pretty good to me...
| Use #include <iostream> - iostream.h is not standard and may differ from the standard behaviour.
See e.g. the C++ FAQ lite entry on the matter.
|
1,911,112 | 1,939,455 | Remote C++ Debugging with RSE | I'm stuck after step 3 in trying to setup remote cross-debugging with Eclipse/RSE:
Installed RSE 3.1 on Eclipse 3.5
Setup a SSH connection profile to my remote device
built binaries using a cross-compiler
Now I can't find the Eclipse option to transfer the binaries to my device and debug using gdb. Under Debug Configurations, I can't find find a "Remote CDT Launch" or " C/C++ Remote Application" referenced by other tutorials.
The only Debug Configuration options I see are the standard "C/C++ Application", "C/C++ Attach", "C/C++ PostMoterm", and "Launch Group".
What should I do next?
| I have not used the remote launch/debug facilities, but maybe these slides from EclipseCon 2008 can help you.
The remote launch was AFAIK moved into CDT itself for Galileo.
Here's the FAQ entry from RSE about remote debugging.
|
1,911,117 | 1,911,160 | Is there a use for uninitialized pointers in C or C++? | In one of the comments in this question, it was brought out that initializing C++ pointers by default would break compatibility with C.
That's fine, but why would something like this matter? I would think the only time it would actually matter is if I wanted an uninitialized pointer for some reason. But I can't think of a reason why I would want to have that.
Is there a use for uninitialized pointers? Or is the compatibility issue merely one of compatible behavior (i.e., not increasing overhead) and not one of breaking code?
| This is a very specialized optimized case for Video Games (basically an embedded system). We used to use them for Load-In-Place data behavior in our Video Games to speed up loading (and avoid fragmentation).
Basically we would create console-side (Playstation) objects in a PC cooker. Then to reduce fragmentation overload, we would pack the data objects in a contiguous buffer with a single alloc. References to the data objects in this buffer would then be changed to subtract the base from pointers to offsets (unfix call -- we also had a virtual fix / unfix calls that took the buffer base and could convert between offsets and pointers).
When we loaded the data, it loaded in one large block. All data referenced by the root was off the root object. We could do an inplace "new" on the the root that would initialize the proper VF tables for the object and fixup all the attached blocks (by doing inplace new and then fixing up attached blocks respectively).
We needed the constructors called (in place new) to generate the proper VF-Tables in the objects. However, if the pointers were automatically cleared to NULL during the constructor, we would have lost the offset data and not been able to recreate the pointers between the objects within the contiguous block.
FWIW, this is a common technique in the Video Game world. This Gamasutra article (not written by me or my coworkers) explains in detail the similar thing they did at another company:
Also, this topic of discussion on SourceForge.
There have even been several GDC (Game Developer Conference) talks on the subject.
Searching on Google for "load-in-place" will give many other examples of people using this technique that basically requires uninitialized pointers.
NOTE: Currently, this is the only response that actually answers the question asked ("Is there a use for uninitialized pointers in C or C++?") by giving a specific use for pointers that must remain unitialized.
All the other responses are better answers for the original question referenced ("[C++] Why aren’t pointers initialized with NULL by default?") that caused the poster to ask this question.
|
1,911,162 | 1,911,187 | Can't compile std::list iterator with template | When I try to compile this I get this error:
error: expected `;' before 'it'
Why I can't declare this iterator? Where is the problem?
#include <list>
template <typename Z>
class LBFuncBase: public LBBaseBlock<Z>
{
void Something() {
std::list<LBBaseBlock< Z >* >::iterator it;
}
};
| Try:
typename std::list<LBBaseBlock< Z >* >::iterator it;
Edit:
See "Why do you sometimes need to write typename" for an explanation.
|
1,911,203 | 1,911,222 | way to implement IPC | what is the preferred way to implement IPC over windows ?
i know of several like : named pipe, shared memory, semaphors ? , maybe COM (though i'm not sure how)...
i wanted to know what's considered the most robust,fast,least error prone and easy to maintain/understand.
| Take a look at boost::interprocess.
Shared memory is probably the fastest in general, but somewhat error-prone and limited to local processes.
COM is fully versioned and automatically supports remote IPC, but obviously it's platform-specific.
For a large-scale application you might want to consider something like ActiveMQ or OpenMQ.
|
1,911,260 | 1,911,276 | File-specific compilation options in Visual Studio 2008 | If I had a project structured like this...
a.cpp
b.cpp
c.cpp
...and I wanted to compile a.cpp and b.cpp with one set of compiler options, and c.cpp with another set, how would I do that?
| I think the easiest way would be to separate them into different projects based on the compiler options you require, and then set up your dependencies appropriately to link them all into your final executable.
|
1,911,434 | 1,911,472 | C++ fancy template code problem | I try to get a (for me) rather complex construct of templated code to work.
what i have:
a class shaderProperty of generic type
class IShaderProperty {
public:
virtual ~IShaderProperty() {}
};
struct IShaderMatth; //forward declaration
template<typename ShadeType>
struct ShaderMatth;//forward declaration
template <typename T>
class ShaderProperty : public IShaderProperty
{
public:
template <typename SomeType>
inline T getValue(ShaderMatth<SomeType>* shaderMatth){
pair<map<void*, IShaderMatth>::iterator,bool> success = shaderMatth->properties.insert(make_pair((void*)this, ShaderMatth<T>(m_shader)));
assert(success.second);
return m_shader->shade((ShaderMatth<T>*)&(*success.first));
}
};
and the class ShaderMatth, which is also of generic type, and stores a map whereas the void* pointer used as key is actually a pointer to a ShaderProperty. Code for ShaderMatth:
#include "ShaderProperty.h"
struct IShaderMatth {
virtual ~IShaderMatth() {}
map<void*, IShaderMatth> properties;
...
};
template <class ReturnType>
struct ShaderMatth : public IShaderMatth{
ShaderMatth(IShader<ReturnType>* shaderPtr){shader=shaderPtr};
~ShaderMatth(void);
IShader<ReturnType>* shader;
};
now the error occurs on the first line of function inline T getValue()
i get an
Error C2027 use of undefined type 'ShaderMatth<ShadeType>'
but i don't understand why.. I have the forward declaration of templated struct ShaderMatth, and in the second bunch of code i include the first bunch of code, so the forward reference should work out, no?
I'm hanging - please help :)
| Forward declaring ShaderMatth is not enough to use the code shaderMatth->properties.
It must be defined before that line.
|
1,911,561 | 1,911,593 | Resize a file (down) | I'm attempting to shrink a file in place.
I'm replacing the contents of one file with those of another and when I'm done I want to make sure if the source file is smaller than the dest file, the dest file shrinks correctly.
(Why: because the dest file is a backup and writing to the media is very expensive, so I only write the deltas to the backup)
1.) HANDLE hDest =(HANDLE)_get_osfhandle( fileno(backupFile.GetBufferedHandle()) );
2.) DWORD startingSize = GetFileSize(hDest, NULL);
3.) DWORD dwPtr = SetFilePointer(hDest, newSize, NULL, FILE_BEGIN);
4.) int err = GetLastError();
5.) if (dwPtr != INVALID_SET_FILE_POINTER)
6.) { err = SetEndOfFile(hDest);
7.) if(err == 0)
8.) err = GetLastError();
9.) err = SetFileValidData(hDest, newSize);
10.) }
11.) DWORD endingSize = GetFileSize(hDest, NULL);
I'm getting an error on line 8 that is 1224... I'm wondering if anyone can tell me why, or suggest a better approach.
| "net helpmsg 1224" -> The requested operation cannot be performed on a file with a user-mapped section open.
And from MSDN for SetEndOfFile:
If CreateFileMapping is called to
create a file mapping object for
hFile, UnmapViewOfFile must be called
first to unmap all views and call
CloseHandle to close the file mapping
object before you can call
SetEndOfFile.
|
1,911,563 | 1,912,468 | thread synchronization | let's say i have a blocking method , let's call in Block().
as i don't want my main thread to block i might create a worker thread, that instead will call Block.
however, i have another condition.
i want the call to block to return in 5 seconds top, otherwise, i want to let the main thread know the call to Block failed and to exit the worker thread.
what would be the best solution to that scenario?
i thought something like that:
create a workher thread, in the worker thread to create a timer object with 5 seconds,
and in addition to call gettickcount before and after the call to Block and calculate the delta.
in addition i will define a boolean IsReturned indication whether the Block function returned already.
after the Block call to set it true.
according to that boolean in the Timer Function i decide how to proceed :
if the boolean is true i do nothing.
if the boolean is false i can queue an APC OnFailure or maybe signal Sucess event on the main thread, and exit the worker thread forcfully (the thing is i'm not sure if i can do that)
in addition after the block function return i check whether the delta is lett then 5 sec
and queue an APC OnSucess. (the question is does exiting the caller thread cancels the timer also ? cause basically after that the timer is useless )
p.s - if i can know for sure that i can cancel the worker thread within the timer function i don't think i even need the gettickcount stuff.
thanks!
| I would suggest using the boost::threads library for this. You can periodically check if the blocking thread is joinable (ie, still working) and then interrupt it after five seconds. You will then need to write the blocking function to handle that interruption and cleanly exit.
#include <boost/thread/thread.hpp>
void Block(void)
{
//Do work and periodically call boost::this_thread::sleep()
try
{
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}
catch(boost::thread_interrupted const&)
{
return;
}
}
int main(int argc, char *argv[])
{
boost::thread blockThread(Block); //If Block takes arguments, just add them as arguments to the constructor.
time_t startTime = time(NULL);
while(true)
{
if(blockThread.joinable() && (time(NULL) - startTime) > 5)
{
blockThread.interrupt();
}
//Do whatever you want while waiting for the thread to finish.
}
}
Edit: Check the Thread Management documentation for more interruption points and the definition for the boost threads class.
Edit2: If you don't need to do any work in the main thread while waiting for the blocking thread to complete, and there is no convenient place to handle interrupts in Block() you can explicitly kill the thread with something like this:
void Block(void)
{
//Do work
}
int main(args)
{
boost::thread blockThread(Block);
//timed_join() returns false if the thread is still running after the specified time.
if(!blockThread.timed_join(boost::posix_time::milliseconds(5000)))
{ //detach() will kill the thread, any memory initialised in Block() will not be freed, any locals may or may not be freed either.
blockThread.detach();
}
}
|
1,911,572 | 1,911,629 | Would VS2008 c++ compiler optimize the following if statement? | if (false == x) { ...}
as opposed to:
if (!x) { ... }
and
if (false == f1()) { ...}
as opposed to:
if (!f1()) { ... }
I think the if(false == ... version is more readable. Do you agree, or have another trick you can propose? Will it be just as fast? Thanks.
This is why I do not like !x:
if (25 == a->function1(12345, 6789) &&
45 == b->function1(12345, 6789) &&
!c->someOtherFunction(123)) { ... }
The following seems better:
if (25 == a->function1(12345, 6789) &&
45 == b->function1(12345, 6789) &&
false == c->someOtherFunction(123)) { ... }
| A good compiler should generate the same code for both code blocks.
However, instead of worrying about false == f1() vs. !f1(), you should be way more worried about the short-circuit evaluation in this example:
if (25 == a->function1(12345, 6789) &&
45 == b->function1(12345, 6789) &&
!c->someOtherFunction(123)) { ... }
Certain compilers will generate code that will skip the execution of b->function1() and c->someOtherFunction(), if a->function1() call happens to evaluate to something different than 25 - the reason being, the compiler already knows the outcome of the whole if () statement at that point, so it can jump at the right place.
If your code depends on a state being modified by any of the skipped functions, you might get nasty surprises.
|
1,911,654 | 1,911,946 | Use of a Union to avoid Dynamic Allocation Headaches | I'm curious if it's a good idea to use a union when accessing Win32 APIs that return variable length structures, to avoid manually managing the allocated memory.
Consider the following:
void displayServices(std::wostream& log, std::tr1::shared_ptr<void> manager, LPENUM_SERVICE_STATUS currentServiceToDisplay, DWORD number, bool whitelist)
{
static union //Don't care about being thread safe
{
QUERY_SERVICE_CONFIG svcConfig;
unsigned char bufferSizer[8000];
};
for(DWORD idx = 0; idx < number; currentServiceToDisplay++, idx++)
{
DWORD garbage = 0;
std::tr1::shared_ptr<void> currentServiceHandle(
OpenService(reinterpret_cast<SC_HANDLE>(manager.get()), currentServiceToDisplay->lpServiceName, SERVICE_QUERY_CONFIG),
serviceCloser);
QueryServiceConfig(reinterpret_cast<SC_HANDLE>(currentServiceHandle.get()),
&svcConfig, 8000, &garbage);
//Use svcConfig for something here.
}
}
Are there any major issues with this?
| One problem with your union approach is that the whole idea of using an union is rather forced and completely unnecessary. All you seem to want to do is the replace dynamic memory allocation with a local static buffer of some "large" size. Then just do it explicitly
unsigned char buffer[8000];
QUERY_SERVICE_CONFIG *svcConfig = (QUERY_SERVICE_CONFIG *) buffer;
...
QueryServiceConfig(reinterpret_cast<SC_HANDLE>(currentServiceHandle.get()),
svcConfig, sizeof buffer, &garbage);
// Use `svcConfig` here, keeping in mind it is a pointer now
What you were trying to achive by using union specifically is not clear to me. Do you think that the approach with the union is somehow more elegant? I don't think so.
Update: It has been noted in one of the comments that this approach allegedly might not work with a compiler performing strict aliasing optimizations. The comment is absolutely incorrect for more than one reason. Firstly, the above approach does not rely on any aliasing-dependent behavior at all, since all access is supposed to be performed through svcConfig pointer and svcConfig pointer only. Secondly, strict aliasing optimizations are never performed if the aliased data is a character array. The language specification explicitly permits aliased access through character arrays, which is why all optimizing compilers disable their strict aliasing optimizations when a character array is involved. Any compiler that fails to do so is broken and thus not worth consideration.
|
1,911,777 | 1,911,833 | C++ problem with std::pair and forward declarations | Unfortunately I still got a problem with my templated code from here:
C++ fancy template code problem
on line 49 in the file 'utility':
error C2440: 'Initializing': cannot convert from 'const int' to 'IntersectionData *'
error C2439: 'std::pair<_Ty1,_Ty2>::second': member could not be initialized
how could i figure out where the problem is? the only place i use a pair with 'IntersectionData*' is here:
#include "MRMaterialMatth.h"
#include "IntersectionData.h"
using namespace std;
struct IShaderMatth {
virtual ~IShaderMatth() {}
vector<pair<MaterialMatth,IntersectionData*> > traceCols;
};
and there are not any other compiler errors
how can I track down this?
//edit: utility is not my code. it must be from std.. the code of line 49 looks like this:
template<class _Other1,
class _Other2>
pair(const pair<_Other1, _Other2>& _Right)
: first(_Right.first), second(_Right.second)
{ // construct from compatible pair
}
line 49 is the line of the comment
edit2:
the only places where i change something about the content of tracecols look like this:
IntersectionData* iDataOut = NULL;
if(newIData_out!=NULL)
{
iDataOut = new IntersectionData(*iData);
}
traceCols->push_back(make_pair(MaterialMatth(),iDataOut));
and
if(traceCols){
traceCols->push_back(make_pair(MaterialMatth(), NULL));
}
and
if(traceCols)
{
(*traceCols)[traceCols->size()].second = new IntersectionData(*newIData);
}
is NULL the problem? it's a pointer, so i should be allowed to create a pair with NULL, no??
| Try explicitly casting the NULL to IntersectionData * in your call to make_pair().
if(traceCols){
traceCols->push_back(make_pair(MaterialMatth(), (IntersectionData *)NULL));
}
|
1,911,822 | 1,911,883 | Using istream_iterator and reading from standard input or file | I'm writing in Microsoft Visual C++ and I'd like my program to either read from standard input or a file using the istream_iterator. Googling the internets hasn't shown how simple I think it must be. So for example, I can write this pretty easily and read from standard input:
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main()
{
istream_iterator<string> my_it(cin);
for (; my_it != istream_iterator<string>(); my_it++)
printf("%s\n", (*my_it).c_str());
}
Or I can write this and read from a file:
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
ifstream file(argv[1]);
istream_iterator<string> my_it(file);
for (; my_it != istream_iterator<string>(); my_it++)
printf("%s\n", (*my_it).c_str());
}
But how do I combine these two so that a simple (argc == 2) check lets me initialize my input stream iterator with either a file stream or stdin and go on about my merry way?
| You can assign to the iterator after constructing it:
int main(int argc, char** argv)
{
ifstream file;
istream_iterator<string> my_it;
if(argc == 2) {
file.open(argv[1]);
my_it = istream_iterator<string>(file);
} else {
my_it = istream_iterator<string>(cin);
}
}
|
1,911,950 | 1,911,960 | How to customize windows default right click pop-up menu | I have two questions. My first one is, that how can i "put" something into the default windows right click pop-up menu? I mean, if i click with the right mouse button on an .exe, then the default things appers(like cut, copy, send to, run as...), but how can i put there one extra line, like "MyApp", which will start my application? I want to do all this in c++.
My second question is, how can i get the filename (or the full path) on which i have started MyApp from the pop-up menu?
Thank in advance!
kampi
| 1) Sounds like you're looking to simply alter or add to the context menu that is provided by Windows Explorer. It's really just a matter of registry settings. See here for a good example.
2) If you follow the zip example of the link above you'll see that the path to the target file is passed to the zip application. Your application, if it accepts arguments can similarly get the path to the file that is being open.
|
1,912,047 | 1,912,082 | Difference between a program that crashes and program that hangs | What is the difference (or causes) between a program that crashes and a program that hangs (becomes unresponsive) in C++?
For sure, accessing invalid memory causes a program to crash. Deadlock in threads may cause a program to hang. What are the other causes?
Does exhausting all memory causes a program to hang? or crash? I'm a bit confused between the differences and their causes.
| Crashing is normally caused by an illegal instruction, e.g. accessing invalid memory, dividing by zero, etc. Usually this manifests itself as a well-known exception which is handled by the operating system.
Hanging can be broken up into 2 fairly high level categories:
Deadlock, usually caused by 2 threads competing for a resource, each requiring a resource held by the other thread to be released. A common cause of this is acquiring multiple locks in inconsistent orders within multiple threads, leading to the common ABBA deadlock pattern (and no this has nothing to do with Swedish pop music).
Livelock, which means that the code is still actively running, but you have reached a state that you cannot leave. For example:
The state of 2 processes/threads keep changing, never reaching an end condition
A while loop where the exit condition will never be satisfied, or an indefinite loop (although this is stretching the definition of "livelock").
Update based on question comment
@Pop, Kristo: Am actually checking on
a code that hangs but I see some
problems on memory leak. But I'm not
really sure if memory leak causes a
program to hang. – jasonline
A memory leak can cause a program to crash, but this depends on various factors:
Size of leak
Frequency of leak
Lifetime of application
Memory leaks may result in 2 bad things - a continual increase in memory usage by the process, and memory fragmentation. Both of these can result in failure to allocate memory down the line, if the OS cannot provide a contiguous block of memory.
In C++, if the new operator fails to allocate memory, a std::bad_alloc exception will be thrown. This will most likely be caught by the OS, resulting in a crash (unless you have written a specific handler in your application for this exception, and are able to handle it more gracefully).
|
1,912,056 | 1,912,120 | VisualStudio C++ Linker problem with template classes | I still can't get it to work..
After I had to separate implementation from definition of one of my generic classes because of a forward declaration, i now get Linker errors when trying to build.
IShader.h:
template <typename ShadeType>
class IShader {
public:
template <typename T>
bool getProperty(const std::string& propertyName, ShaderProperty<T>** outProp);
};
so it's a generic class with a generic member function with a different generic type
implementation looks like this:
#include "MRIShader.h"
template <typename ShadeType> template <typename T>
bool IShader<ShadeType>::getProperty(const std::string& propertyName, ShaderProperty<T>** outProp){
std::map<std::string, IShaderProperty* >::iterator i = m_shaderProperties.find(propertyName);
*outProp = NULL;
if( i != m_shaderProperties.end() ) {
*outProp = dynamic_cast<ShaderProperty<T>*>( i->second );
return true;
}
return false;
}
but i get Linker errors like this one:
error LNK2001: Nicht aufgelöstes externes Symbol ""public: bool __thiscall IShader<class A_Type>::getProperty<bool>(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class ShaderProperty<bool> * *)" (??$getProperty@_N@?$IShader@VA_Type@@@@QAE_NABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAPAV?$ShaderProperty@_N@@@Z)". SceneParser.obj
for bool, but also for many other types.
I already read through this article:
http://www.parashift.com/c++-faq-lite/templates.html
but adding
templace class IShader<bool>;
in the end of IShader.cpp doesn't solve the problem.
I also tried to add the 'export' keyword before the keyword 'template' in the implementation, but this just gives me a syntax error.
What's the proper way to declare and implement my template class, which has templated member methods (with a different template type!) in separate files (.h and .cpp) without getting Linker errors?
thanks!
| Your only providing a linkable object for the class in the translation unit, but the member function is templated on another parameter and has also to be explicitly specified.
I don't know if there is a more elegant way, but one compilable version would be:
template bool IShader<bool>::getProperty<bool>
(const std::string& propertyName,
ShaderProperty<bool>** outProp);
VC8 and GCC 3.4 both allow to leave out the <bool> after the function name. I'm however not sure about the correct syntax in that case.
But as long as you're not having problems with the compilation time in a big project, save yourself the trouble and put the method definitions (marked inline) in a header.
If you're just worried about the size of the header file, move the definitions in another header file, e.g. IShaderImpl.h, that you include at the end of IShader.h.
Quick sample to remove doubts:
// IShader.h
template<typename T>
struct ShaderProperty {};
template <typename T>
class IShader {
public:
template <typename U>
void getProperty(ShaderProperty<U>**);
};
// IShader.cpp
#include <iostream>
#include "IShader.h"
template<typename T> template<typename U>
void IShader<T>::getProperty(ShaderProperty<U>**)
{ std::cout << "moo" << std::endl; }
template class IShader<bool>;
template void IShader<bool>::getProperty(ShaderProperty<bool>**);
// main.cpp
#include "IShader.h"
int main() {
IShader<bool> b;
ShaderProperty<bool>** p;
b.getProperty(p);
}
|
1,912,106 | 1,912,116 | Nominal case first vs. Positive boolean expressions | As the topic states, sometimes these issues conflict. For example...
In this case, the nominal case is first, but the expression is negative.
if ( !foo.IsDead() ) {
DoThis();
} else {
DoThat();
}
In this case, the expression is positive, but the nominal case is last.
if ( foo.IsDead() ) {
DoThat();
} else {
DoThis();
}
Of course, a third option would be to flip around the IsDead function to be IsAlive(). I'd like to hear others' thoughts on these 3 choices when they encounter them in coding. Do you go with nominal, positive, or fix the whole thing by flipping the boolean itself.
| I prefer option two as it's slightly clearer / easier to read.
But you're heading for religious war territory I suspect.
In terms of flipping the name of the function, I'd only change if isAlive() is the most likely outcome. That is, I think the code is clearer if the most likely outcome is your boolean expression equating to true. The least likely (false) should come second. It it's 50/50 then I wouldn't worry.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.