question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,379,427 | 2,379,522 | multiple inheritance: unexpected result after cast from void * to 2nd base class | My program needs to make use of void* in order to transport data or objects in dynamic invocation situation, so that it can reference data of arbitrary types, even primitive types. However, I recently discovered that the process of down-casting these void* in case of classes with multiple base classes fails and even crashes my program after invoking methods on these down casted pointers even if the memory addresses seem to be correct. The crash happens during access to "vtable".
So I have created a small test case, environment is gcc 4.2 on Mac OS X:
class Shape {
public:
virtual int w() = 0;
virtual int h() = 0;
};
class Square : public Shape {
public:
int l;
int w() {return l;}
int h() {return l;}
};
class Decorated {
public:
int padding;
int w() {return 2*padding;}
int h() {return 2*padding;}
};
class DecoratedSquare : public Square, public Decorated {
public:
int w() {return Square::w() + Decorated::w();}
int h() {return Square::h() + Decorated::h();}
};
#include <iostream>
template <class T> T shape_cast(void *vp) {
// return dynamic_cast<T>(vp); // not possible, no pointer to class type
// return static_cast<T>(vp);
// return T(vp);
// return (T)vp;
return reinterpret_cast<T>(vp);
}
int main(int argc, char *argv[]) {
DecoratedSquare *ds = new DecoratedSquare;
ds->l = 20;
ds->padding = 5;
void *dsvp = ds;
std::cout << "Decorated (direct)" << ds->w() << "," << ds->h() << std::endl;
std::cout << "Shape " << shape_cast<Shape*>(dsvp)->w() << "," << shape_cast<Shape*>(dsvp)->h() << std::endl;
std::cout << "Square " << shape_cast<Square*>(dsvp)->w() << "," << shape_cast<Square*>(dsvp)->h() << std::endl;
std::cout << "Decorated (per void*) " << shape_cast<Decorated*>(dsvp)->w() << "," << shape_cast<Decorated*>(dsvp)->h() << std::endl;
std::cout << "DecoratedSquare " << shape_cast<DecoratedSquare*>(dsvp)->w() << "," << shape_cast<DecoratedSquare*>(dsvp)->h() << std::endl;
}
produces the following output:
Decorated (direct)30,30
Shape 30,30
Square 30,30
Decorated (per void*) 73952,73952
DecoratedSquare 30,30
As you can see, the "Decorated (per void*)" result is completely wrong. It should also be 30,30 like in the first line.
Whatever cast method I use in shape_cast() I will always get the same unexpected results for the Decorated part. Something is completely wrong with these void *.
From my understanding of C++ this should be actually working. Is there any chance to get this to work with the void*? Can this be a bug in gcc?
Thanks
| It's not a compiler bug - it's what reinterpret_cast does. The DecoratedSquare object will be laid out in memory something like this:
Square
Decorated
DecoratedSquare specific stuff
Converting a pointer to this to void* will give the address of the start of this data, with no knowledge of what type is there. reinterpret_cast<Decorated*> will take that address and interpret whatever is there as a Decorated - but the actual memory contents are the Square. This is wrong, so you get undefined behaviour.
You should get the correct results if you reinterpret_cast to the correct dynamic type (that is DecoratedSquare), then convert to the base class.
|
2,379,595 | 21,006,138 | Simple libtool alternative? | Being perfectly satisfied with old-style Makefiles, I am looking for a simple alternative to libtool. I do not want to switch to automake, and I keep running into problems with libtool when I try to use it directly. The latest one is 'unsupported hardcode properties', and I am getting fed up with the lack of complete documentation that just tells me what is wrong this time...
I only want to compile a bunch of .o files with the right flags and then link them into a shared library, such that it works on as many platforms as possible. Is there anything out there that does just that and not force me to switch all of my other tools at the same time?
| There's jlibtool (which has nothing to do with java).
It's written in C, and can just be bundled with your source.
It was originally an apache project, but whoever was working it there seems to of abandoned it around 2004.
It was taken over by FreeRADIUS project maintainer Alan Dekok, who modernised the code and fixed a few niggling issues. We use it for the FreeRADIUS project (>= 3.0.0) to do all the build time linking.
|
2,379,634 | 2,379,681 | binary read/write runtime failure | I've looked at binary reading and writing objects in c++ but are having some problems. It "works" but in addition I get a huge output of errors/"info".
What I've done is
Person p2;
std::fstream file;
file.open( filename.c_str(), std::ios::in | std::ios::out | std::ios::binary );
file.seekg(0, std::ios::beg );
file.read ( (char*)&p2, sizeof(p2));
file.close();
std::cout << "Name: " << p2.name;
Person is a simple struct containing string name and int age. When I run the program it outputs "Name: Bob" since I have already made a program to write to a file (so the object is already in filename).
IN ADDITION to outputting the name it also outputs:
* glibc detected * program: double free og corruption (fastttop): ***
Backtrace:
...
Memory map:
...
Abort
| Is the name string in the Person struct a character array or a STL string? You can't fill in an STL String by binary reading data over top of it, since the data format is not serializable (contains pointers)
|
2,379,806 | 2,379,903 | Using condition variable in a producer-consumer situation | I'm trying to learn about condition variables and how to use it in a producer-consumer situation. I have a queue where one thread pushes numbers into the queue while another thread popping numbers from the queue. I want to use the condition variable to signal the consuming thread when there is some data placed by the producing thread. The problem is there are times (or most times) that it only pushes up to two items into the queue then hangs. I have indicated in the produce() function where it stops when running in debug mode. Can anyone help me point out why this is happening?
I have the following global variables:
boost::mutex mutexQ; // mutex protecting the queue
boost::mutex mutexCond; // mutex for the condition variable
boost::condition_variable condQ;
Below is my consumer thread:
void consume()
{
while( !bStop ) // globally declared, stops when ESC key is pressed
{
boost::unique_lock lock( mutexCond );
while( !bDataReady )
{
condQ.wait( lock );
}
// Process data
if( !messageQ.empty() )
{
boost::mutex::scoped_lock lock( mutexQ );
string s = messageQ.front();
messageQ.pop();
}
}
}
Below is my producer thread:
void produce()
{
int i = 0;
while(( !bStop ) && ( i < MESSAGE )) // MESSAGE currently set to 10
{
stringstream out;
out << i;
string s = out.str();
boost::mutex::scoped_lock lock( mutexQ );
messageQ.push( s );
i++;
{
boost::lock_guard lock( mutexCond ); // HANGS here
bDataReady = true;
}
condQ.notify_one();
}
}
| You have to use the same mutex to guard the queue as you use in the condition variable.
This should be all you need:
void consume()
{
while( !bStop )
{
boost::scoped_lock lock( mutexQ);
// Process data
while( messageQ.empty() ) // while - to guard agains spurious wakeups
{
condQ.wait( lock );
}
string s = messageQ.front();
messageQ.pop();
}
}
void produce()
{
int i = 0;
while(( !bStop ) && ( i < MESSAGE ))
{
stringstream out;
out << i;
string s = out.str();
boost::mutex::scoped_lock lock( mutexQ );
messageQ.push( s );
i++;
condQ.notify_one();
}
}
|
2,379,859 | 2,379,868 | In C++, what does & mean after a function's return type? | In a C++ function like this:
int& getNumber();
what does the & mean? Is it different from:
int getNumber();
| Yes, the int& version returns a reference to an int. The int version returns an int by value.
See the section on references in the C++ FAQ
|
2,379,867 | 2,380,280 | Simulating key press events in Mac OS X | I'm writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent function to create the event. The problem is that this function needs a Mac keycode, and what I have is a code that represents the specific key. So, for example, I receive:
KEY_CODE_SHIFT or KEY_CODE_A - these are both numeric constants defined somewhere.
I need to take these constants and turn them into CGKeyCode values.
My current attempt uses code similar to this SO question. The problem is that it only works for printable characters. If all else fails, I'm not above hard coding the conversion, but that would mean that I'd need a table of possible CGKeyCode values, which I have not yet been able to find.
Any ideas?
| Here's code to simulate a Cmd-S action:
CGKeyCode inputKeyCode = kVK_ANSI_S;
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, inputKeyCode, NO);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);
CFRelease(saveCommandUp);
CFRelease(saveCommandDown);
CFRelease(source);
A CGKeyCode is nothing more than an unsigned integer:
typedef uint16_t CGKeyCode; //From CGRemoteOperation.h
Your real issue will be turning a character (probably an NSString) into a keycode. Fortunately, the Shortcut Recorder project has code that will do just that in the SRKeyCodeTransformer.m file. It's great for transforming a string to a keycode and back again.
|
2,380,071 | 2,380,358 | All things equal what is the fastest way to output data to disk in C++? | I am running simulation code that is largely bound by CPU speed. I am not interested in pushing data in/out to a user interface, simply saving it to disk as it is computed.
What would be the fastest solution that would reduce overhead? iostreams? printf? I have previously read that printf is faster. Will this depend on my code and is it impossible to get an answer without profiling?
This will be running in Windows and the output data needs to be in text format, tab/comma separated, with formatting/precision options for mostly floating point values.
| My thought is that you are tackling the wrong problem. Why are you writing out vast quantities of text formatted data? If it is because you want it to be human readable, writing a quick browser program to read the data in binary format on the fly - this way the simulation application can quickly write out binary data and the browser can do the grunt work of formatting the data as and when needed. If it is because you are using some stats package to read and analyse text data then write one that inputs binary data.
|
2,380,143 | 2,380,195 | C++ metaprogramming with templates versus inlining | Is it worth to write code like the following to copy array elements:
#include <iostream>
using namespace std;
template<int START, int N>
struct Repeat {
static void copy (int * x, int * y) {
x[START+N-1] = y[START+N-1];
Repeat<START, N-1>::copy(x,y);
}
};
template<int START>
struct Repeat<START, 0> {
static void copy (int * x, int * y) {
x[START] = y[START];
}
};
int main () {
int a[10];
int b[10];
// initialize
for (int i=0; i<=9; i++) {
b[i] = 113 + i;
a[i] = 0;
}
// do the copy (starting at 2, 4 elements)
Repeat<2,4>::copy(a,b);
// show
for (int i=0; i<=9; i++) {
cout << a[i] << endl;
}
} // ()
or is it better to use a inlined function?
A first drawback is that you can't use variables in the template.
| That's not better. First of all, it's not really compile time, since you make function calls here. If you are lucky, the compiler will inline these and end up with a loop you could have written yourself with much less amount of code (or just by using std::copy).
|
2,380,153 | 2,380,181 | Finding "dead code" in a large C++ legacy application | I'm currently working on a large and old C++ application that has had many developers before me. There is a lot of "dead code" in the project, classes and functions that aren't used by anyone anymore.
What tools are available for C++ to make a analysis of large code base to detect and refactor dead code? Note: I'm not talking about test coverage tool like gcov.
How do you find dead code in your project?
| You'll want to use a static analysis tool
StackOverflow: What open source C++ static analysis tools are available?
Wikipedia: List of tools for static code analysis
The main gotcha I've run into is that you have to be careful that any libraries aren't used from somewhere that you don't control/have. If you delete a function from a class that gets used by referencing a library in your project you can break something that you didn't know used the code.
|
2,380,185 | 2,380,521 | Function pointers and unknown number of arguments in C++ | I came across the following weird chunk of code.Imagine you have the following typedef:
typedef int (*MyFunctionPointer)(int param_1, int param_2);
And then , in a function , we are trying to run a function from a DLL in the following way:
LPCWSTR DllFileName; //Path to the dll stored here
LPCSTR _FunctionName; // (mangled) name of the function I want to test
MyFunctionPointer functionPointer;
HINSTANCE hInstLibrary = LoadLibrary( DllFileName );
FARPROC functionAddress = GetProcAddress( hInstLibrary, _FunctionName );
functionPointer = (MyFunctionPointer) functionAddress;
//The values are arbitrary
int a = 5;
int b = 10;
int result = 0;
result = functionPointer( a, b ); //Possible error?
The problem is, that there isn't any way of knowing if the functon whose address we got with LoadLibrary takes two integer arguments.The dll name is provided by the user at runtime, then the names of the exported functions are listed and the user selects the one to test ( again, at runtime :S:S ).
So, by doing the function call in the last line, aren't we opening the door to possible stack corruption? I know that this compiles, but what sort of run-time error is going to occur in the case that we are passing wrong arguments to the function we are pointing to?
| There are three errors I can think of if the expected and used number or type of parameters and calling convention differ:
if the calling convention is different, wrong parameter values will be read
if the function actually expects more parameters than given, random values will be used as parameters (I'll let you imagine the consequences if pointers are involved)
in any case, the return address will be complete garbage, so random code with random data will be run as soon as the function returns.
In two words: Undefined behavior
|
2,380,258 | 2,380,459 | Crossplatform iPhone / Android code sharing | Simply put: What is the most effective way to share / reuse code between iPhone and Android builds?
The two most common scenarios I think would be:
Blank slate new project, knowing ahead of time there is a large chunk of reusable logic that needs to run on each device.
Existing iPhone code base, porting of C, C++ and Objective-C to the Android NDK or otherwise.
Yes of course in a perfect world all apps would just plug into the magical cloud and all the reusable logic would be up in Google App Engine or some web services, but that is not the spirit of this question. After experiencing a port of iPhone to Android with no code reuse at all second-hand and seeing the pain that person had to endure, I'd like to know how other people are avoiding it.
| In my experience, you can use Android NDK to compile C and C++ , so if you use iPhone Obj-C++ (.mm) bindings for a C++/C engine in the iPhone, and in Android you use Java bindings to the same engine, It should be totally possible.
So C++/C engine ( almost same codebase for Android and iPhone ) + Thin bindings layer = Portable code.
|
2,380,307 | 2,412,341 | Why does my std::wofstream write ansi? | I've got wide string and I'm writing it to a wofstream that I opened in out|binary mode. When I look in the resultant file, it's missing every other byte.
I was expecting that when I opened the file in visual studio with the binary editor that I'd see every other byte as a zero, but I'm not seeing the zeros.
Do you know what I'm missing?
Thanks.
The code is something like this:
CAtlStringW data = L"some data";
wofstream stream("c:\hello.txt", ios_base:out|ios_base:binary);
stream.write( data.GetBuffer(), data.GetLength() );
stream.close();
| When you write to file using output wide stream, what actually happens is that it converts the wide characters to other 8-bit encoding.
If you were using UTF-8 locale it would convert wide strings to UTF-8 encoded text (but MSVC does not provides UTF-8 locales) so generally it would try to convert to some code-page like cp1251 or to ASCII.
|
2,380,520 | 2,401,669 | Hosting a VST/DX instrument in C#/C++? | I'm trying to get a read on the effort level involved in building a barebones virtual instrument host in C++ or C# but I haven't been able to get any hard information. Does anybody know any good starter apps, tutorials, helper libraries for this sort of thing?
If it matters, the goal would be to a) accept incoming MIDI events and b) dispatch them to the virtual instrument. In C++ or C#, if possible.
Thanks!
| To capture incoming Midi events use the C# Midi Toolkit (on codeproject.com) by Leslie Sanford or my MIDI.NET library.
VST.NET allows you to load and communicate with managed and unmanaged VST (2.4) plugins. You can also create managed VST plugins with VST.NET that can run in unmanaged Hosts.
There is also a simple C++ open source VST host available at http://www.hermannseib.com/english/vsthost.htm (down at the bottom of the page)
Hope it helps.
Marc Jacobi
(Author of VST.NET)
|
2,380,574 | 2,380,639 | Are static vars in a method body shared by all instances | class MyClass
{
public:
void method2()
{
static int i;
...
}
};
Will every instance of MyClass share one value i, or will each instance have its own copy?
| static, here, operates as in any regular function.
Which means that i is static within MyClass::method2, so there is one and only one instance of it.
Having one instance of a variable per object is what instance variables are for.
|
2,380,720 | 2,380,738 | Isn't a const variable at namespace scope implicitly static? | I know that static const int x = 42; at namespace scope is equivalent to const int x = 42; because const variables are implicitly static (they must be declared extern to be given external linkage). Every translation unit that includes this declaration gets a local copy of x.
Does this only apply to certain (perhaps integer?) types? I have the following code in a header file:
namespace XXX {
static const char* A = "A";
static const char* B = "B";
static const char* C = "C"; // and so on
}
(PLEASE spare me the comments on why I should not be using C-style strings -- this is legacy code)
This header is included from several source files, and all is fine (each compilation unit gets its own copy of these char*'s). I would have thought that I could remove the static from these, as it is redundant, but when I do, I get link errors about the symbols being already defined in another object. What am I missing here? Are these const char*'s not implicitly static?
| In your example, you are creating a pointer to a constant (block of) char rather than creating a constant pointer to a char. Thus, your pointer isn't constant and so isn't implicitly static.
You need to declare x as const char *const A, which creates a constant pointer to a constant (block of) char.
|
2,380,728 | 2,381,064 | Getting the number of trailing 1 bits | Are there any efficient bitwise operations I can do to get the number of set bits that an integer ends with? For example 1110 = 10112 would be two trailing 1 bits. 810 = 10002 would be 0 trailing 1 bits.
Is there a better algorithm for this than a linear search? I'm implementing a randomized skip list and using random numbers to determine the maximum level of an element when inserting it. I am dealing with 32 bit integers in C++.
Edit: assembler is out of the question, I'm interested in a pure C++ solution.
| Taking the answer from Ignacio Vazquez-Abrams and completing it with the count rather than a table:
b = ~i & (i+1); // this gives a 1 to the left of the trailing 1's
b--; // this gets us just the trailing 1's that need counting
b = (b & 0x55555555) + ((b>>1) & 0x55555555); // 2 bit sums of 1 bit numbers
b = (b & 0x33333333) + ((b>>2) & 0x33333333); // 4 bit sums of 2 bit numbers
b = (b & 0x0f0f0f0f) + ((b>>4) & 0x0f0f0f0f); // 8 bit sums of 4 bit numbers
b = (b & 0x00ff00ff) + ((b>>8) & 0x00ff00ff); // 16 bit sums of 8 bit numbers
b = (b & 0x0000ffff) + ((b>>16) & 0x0000ffff); // sum of 16 bit numbers
at the end b will contain the count of 1's (the masks, adding and shifting count the 1's).
Unless I goofed of course. Test before use.
|
2,380,747 | 2,380,766 | compiler generated constructors | This is just a quick question to understand correctly what happens when you create a class with a constructor like this:
class A
{
public:
A() {}
};
I know that no default constructor is generated since it is already defined but are copy and assignment constructors generated by the compiler or in other words do i need to
declare a private copy constructor and a private assignment operator in order to prevent this from happening?
class A
{
private:
// needed to prevent automatic generation?
A( const A& );
A& operator=( const A& );
public:
A() {}
};
| Yes. The copy constructor, assignment operator, and destructor are always created regardless of other constructors and operators.
If you want to disable one, what you've got there is perfect. It's quite common too.
|
2,380,803 | 2,380,834 | Is the behavior of return x++; defined? | If I have for example a class with instance method and variables
class Foo
{
...
int x;
int bar() { return x++; }
};
Is the behavior of returning a post-incremented variable defined?
| Yes, it's equivalent to:
int bar()
{
int temp = x;
++x;
return temp;
}
|
2,380,839 | 2,380,885 | Internal compiler error and boost::bind | I'm testing a C++ class with a number of functions that all have basically the same form:
ClassUnderTest t;
DATATYPE data = { 0 };
try
{
t.SomeFunction( &data );
}
catch( const SomeException& e )
{
// log known error
}
catch( ... )
{
// log unknown error
}
Since there's a lot of these, I thought I'd write a function to do most of the heavy lifting:
template< typename DATA, typename TestFunction >
int DoTest( TestFunction test_fcn )
{
DATA data = { 0 };
try
{
test_fcn( &data );
}
catch( const SomeException& e )
{
// log known error
return FAIL;
}
catch( ... )
{
// log unknown error
return FAIL;
}
return TRUE;
}
ClassUnderTest t;
DoTest< DATATYPE >( boost::bind( &ClassUnderTest::SomeFunction, boost::ref( t ) ) );
But, the compiler doesn't seem to agree with me that this is a good idea...
Warning 1 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\bind.hpp 1657
Warning 2 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 318
Warning 3 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 326
Warning 4 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 331
Warning 5 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 345
Warning 6 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 350
Warning 7 warning C4180: qualifier applied to function type has no meaning; ignored c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 362
Error 8 fatal error C1001: An internal error has occurred in the compiler. c:\boost\boost_1_41_0\boost\bind\mem_fn.hpp 328
I'm using Visual Studio 2008 SP1.
If anybody can point out what I'm doing wrong, I would appreciate it.
Thanks,
PaulH
| The error is in your code, not in bind. You pass a functor that does not expect any arguments. Instead of your call, do
DoTest< DATATYPE >( boost::bind( &ClassUnderTest::SomeFunction, &t, _1) );
If you omit _1 then bind will create a zero-argument function object, and the member function (which expects a data pointer) will miss one argument when called by bind.
|
2,380,854 | 2,381,190 | Massive amount of object creation in C++ | Is there any pattern how to deal with a lot of object instantiations (40k per second) on a mobile device? I need these objects separately and they cannot be combined. A reusage of objects would probably be a solution. Any hints?
| I think you could consider these design patterns:
Object Pool
Factory
Further info
I hope this help you too: Object Pooling for Generic C++ classes
|
2,380,869 | 2,380,979 | How best to test a Mutex implementation? | What is the best way to test an implementation of a mutex is indeed correct? (It is necessary to implement a mutex, reuse is not a viable option)
The best I have come up with is to have many (N) concurrent threads iteratively attempting to access the protected region (I) times, which has a side effect (e.g. update to a global) so that the number of accesses + writes can be counted to ensure that the number of updates to the global is exactly (N)*(I).
Any other suggestions?
| This reminds me of this question about FIFO semaphore test. In a nutshell my answer was:
Even if you have a specification, maybe it doesn't convey your intention exactly
You can prove that the algorithm fulfills the specification, but not the code (D. Knuth)
Test reveal only the presence of bug, not their absence (Dijkstra)
So your proposition seem reasonably the best to do. If you want to increase your confidence, use fuzzing to randomize scheduling and input.
|
2,380,957 | 2,381,550 | c++ IPC - d3d hook and directshow capture source | I'm writing an app that will basically be like Fraps, but it will push video frames as a DirectShow Capture Source. This will make it easy to stream games on websites like ustream, justin.tv, etc. I'm wondering what the best way to do the interprocess communication would be. Speed is very important. Right now I have a dll that is injected and hooks d3d to grab the frame buffer. I need a way to send that to a directshow filter. DirectShow is really confusing for me, but I've implemented CSource an CSourceStream (in another dll).
| If you want speed, use shared memory. Combine that with COM for normal communication and you got a standard windows IPC approach.
If you want to wrap it up with a more modern C++ style, take a look at Boost.Interprocess' primitives.
|
2,381,112 | 2,421,271 | SharePoint fails to load a C++ DLL on Windows 2008 | I have a SharePoint DLL that does some licensing things and as part of the code it uses an external C++ DLL to get the serial number of the hardisk.
When I run this application on Windows Server 2003 it works fine, but on Windows Server 2008 the whole site (loaded on load) crashes and resets continually. This is not Windows Server 2008 R2 and is the same in 64 or 32 bits.
If I put a Debugger.Break before the DLL execution then I see the code get to the point of the break and then never come back into the DLL again. I do get some debug assertion warnings from within the function, again only in Windows Server 2008, but I'm not sure this is related.
I created a console application that runs the C# DLL, which in turn loads the C++ DLL, and this works perfectly on Windows Server 2008 (although it does show the assertion errors, but I have suppressed these now).
The assertion errors are not in my code but within ICtypes.c, and not something I can debug.
If I put a breakpoint in the DLL it is never hit and the compiler says:
"step in: Stepping over non user code"
If I try to debug into the DLL using Visual Studio.
I have tried wrapping the code used to call the DLL in:
SPSecurity.RunWithElevatedPrivileges(delegate()
But this also does not help.
I have the source code for this DLL so that is not a problem.
If I delete the DLL from the directory I get an error about a missing DLL. If I replace it, back to no error or warning just a complete failure.
If I replace this code with a hardcoded string the whole application works fine.
Any advice would be much appreciated, I can't understand why it works as a console application, yet not when run by SharePoint. This is with the same user account, on the same machine...
This is the code used to call the DLL:
[DllImport("idDll.dll", EntryPoint = "GetMachineId", SetLastError = true)]
extern static string GetComponentId([MarshalAs(UnmanagedType.LPStr)]String s);
public static string GetComponentId()
{
Debugger.Break();
if (_machine == string.Empty)
{
string temp = "";
id= ComponentId.GetComponentId(temp);
}
return id;
}
| This could be security related:
An important point is that it works in a console app.
In a console app RunWithElevatedPrivileges has no effect since it emulates the app pool user for your worker process, a user that should have no special rights on the box itself.
In contrast a console app runs in context of the logged in user.
Try emulating a user with rights like when you run the console application specified here (with Undo() inside try/finally mind you!). When obtaining the token you can create an SPUserToken and establish site context using the SPSite constructor that takes a GUID and a SPUserToken
Theres several examples out there documenting this approach, here for example.
EDIT: oh and the reason it worked on 2003 could be that your app pool account had way too many rights ;-)
|
2,381,119 | 2,381,188 | Parse a string to get the nth field | Im trying to parse the string located in /proc/stat in a linux filesystem using c++
I have lifted and saved the string as a variable in a c++ program
I want to lift individual values from the string. Each value is separated by a space.
I want to know how i would, for example, lift the 15th value from the string.
| std::strings separated by spaces can be automatically parsed from any ostream. Simply throw the entire line into an std::istringstream and parse out the nth string.
std::string tokens;
std::istringstream ss(tokens);
std::string nth;
for (int i = 0; i < 15; ++i)
ss >> nth;
return nth;
|
2,381,719 | 2,381,860 | How to have memfun with two parameters | I want to use this function "EnumWindows(EnumWindowsProc, NULL);".
The EnumWindowsProc is a Callback function:
BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
For this callback I want to use a member function of a class.
e.g:
Class MyClass
{
BOOL CALLBACK My_EnumWindowsProc(HWND hwnd, LPARAM lParam);
void test();
};
So i want to bind the called Callback with my function !!!
I try this:
void MyClass::test()
{
EnumWindowsProc ptrFunc = mem_fun(&MyClass::My_EnumWindowsProc);
EnumWindows(ptrFunc, NULL);
}
It's doesn't work, "mem_fun" can take only one argument !
Is it possible to do that ? else do you know another solution ?
(maybe a solution will be possible with Boost::bind)
| You need to create an Adapter, such as:
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class MyCallback
{
public:
MyCallback() : count_(0) {};
static BOOL CALLBACK CallbackAdapter(HWND, LPARAM);
BOOL Callback(HWND);
unsigned count_;
};
BOOL MyCallback::Callback(HWND wnd)
{
char title[1025] = {};
GetWindowText(wnd, title, sizeof(title)-1);
cout << wnd << "= '" << title << "'" << endl;
++count_;
return TRUE;
}
BOOL MyCallback::CallbackAdapter(HWND wnd, LPARAM lp)
{
MyCallback* that = reinterpret_cast<MyCallback*>(lp);
return that->Callback(wnd);
}
int main()
{
MyCallback cb;
EnumWindows(&MyCallback::CallbackAdapter, reinterpret_cast<LPARAM>(&cb));
cout << "Windows Found: " << cb.count_;
return 0;
}
|
2,381,941 | 2,381,963 | How to get a facet from a std::locale object? | I want to get the numpunct<char> facet for the native locale. I can generate a native locale object by constructing an object with an empty string std::locale native_loc(""), but once I have it how do I get a numpunct from it? The documentation I've found doesn't really show the connection between the two.
| Use use_facet<facet_type>(locale):
std::numpunct<char> const&n = std::use_facet< std::numpunct<char> >(std::locale(""));
|
2,382,122 | 2,382,140 | Long Pointer to Constant Wide String, what's the function of the Long here? | When you have a LPCWSTR, why is it a Long Pointer? There's no Long in it's definition, as far as I know.
Can anybody explain?
| 'Long' is a leftover from Windows-16-bit. In the old days, on DOS and Windows 3.x, most apps were 16 bits and had 16-bit pointers. 32-bit pointers were 'long' and had to be specially declared, and used (in some DOS cases) selectors and not the flat address space.
|
2,382,137 | 2,382,399 | How to unroll a short loop in C++ | I wonder how to get something like this:
Write
copy(a, b, 2, 3)
And then get
a[2] = b[2];
a[3] = b[3];
a[4] = b[4];
I know that C #defines can't be used recursively to get that effect. But I'm using C++, so I suppose that template meta-programming might be appropriate.
I know there is a Boost library for that, but I only want that "simple" trick, and Boost is too "messy".
| The most straightforward solution to this is to write a loop where the start and end values are known:
for(int i = 2; i <= 4; i++) {
a[i]=b[i];
}
I think this is better than any sort of template/runtime-call mixture: The loop as written is completely clear to the compilers' optimizer, and there are no levels of function calls to dig through just to see what's going on.
|
2,382,184 | 2,382,234 | Get a particular text from website | I'm looking for a way if you know the location where to read the text for example say, under a particular category, how would you connect to a website and search & read the text from it?
what steps do i need to follow to learn about that?
| you could use libcurl/cURL for your HTML retrival
|
2,382,834 | 2,382,857 | Discards qualifiers error | For my compsci class, I am implementing a Stack template class, but have run into an odd error:
Stack.h: In member function ‘const T Stack<T>::top() const [with T = int]’:
Stack.cpp:10: error: passing ‘const Stack<int>’ as ‘this’ argument of ‘void Stack<T>::checkElements() [with T = int]’ discards qualifiers
Stack<T>::top() looks like this:
const T top() const {
checkElements();
return (const T)(first_->data);
}
Stack<T>::checkElements() looks like this:
void checkElements() {
if (first_==NULL || size_==0)
throw range_error("There are no elements in the stack.");
}
The stack uses linked nodes for storage, so first_ is a pointer to the first node.
Why am I getting this error?
| Your checkElements() function is not marked as const so you can't call it on const qualified objects.
top(), however is const qualified so in top(), this is a pointer to a const Stack (even if the Stack instance on which top() was called happens to be non-const), so you can't call checkElements() which always requires a non-const instance.
|
2,382,871 | 2,389,681 | Lightweight alternatives to CDT for C++ editing in eclipse | For a few years now, I've been using Eclipse as my all-purpose file editor, regardless of the language I use (which mainly includes C++, Matlab and python, with some XML thrown in for fun).
However, I recently got a new machine with more a recent Eclipse, and the wonderful Colorer plugin, which I previously used, crashes (Which is a separate issue that's apparently specific to my setup - I'll try debug it, but in the meantime I have work to do)
So I've switched to CDT for C++ instead, and I'm having serious performance issues with the editor, especially when copy-pasting or undoing stuff. I understand why CDT is so heavy, but I don't want a full C++ IDE - just something that does decent syntax highlighting.
Are there any lightweight syntax highlighting alternatives to CDT (or Colorer) that do a decent job at C++, without the needless (for me) layer of code completion and all that jazz?
Or, alternatively, any ideas of things I can turn off to turn CDT into a lightning-fast bare-bones editor (I've already turned off the spell-checker and the indexer)
Edited to say that I'm not looking for a replacement editor for Eclipse, except maybe as a short-time fix. If this problem turns out to be unsolvable and I have to learn/configure something new, I'm going to switch to emacs (for all kinds of non-religious reason: it's pretty much standard everywhere, my colleagues already use it, and the person in charge of our standard development setup supports it, so it's really the most reasonable replacement for me) But really, I'd prefer a fix to my poor Eclipse.
| I've finally figured out a work-around to my performance issue.
There is a "scalability" mode in CDT that kicks in when your file is above a certain number of lines (under Preferences-C/C++-Editor-Scalability). By changing the default size to 1, I can disabled the "editor live parsing" that seems to be causing the problem, and get a significant performance boost.
|
2,382,930 | 2,382,972 | C++: allocate block of T without calling constructor | I don't want constructor called. I am using placement new.
I just want to allocate a block of T.
My standard approach is:
T* data = malloc(sizeof(T) * num);
however, I don't know if (data+i) is T-aligned. Furthermore, I don't know if this is the right "C++" way.
How should I allocate a block of T without calling its constructor?
| Firstly, you are not allocating a "block of T*". You are allocating a "block of T".
Secondly, if your T has non-trivial constructor, then until elements are constructed, your block is not really a "block of T", but rather a block of raw memory. There's no point in involving T here at all (except for calculating size). A void * pointer is more appropriate with raw memory.
To allocate the memory you can use whatever you prefer
void *raw_data = malloc(num * sizeof(T));
or
void *raw_data = new unsigned char[num * sizeof(T)];
or
void *raw_data = ::operator new(num * sizeof(T));
or
std::allocator<T> a;
void *raw_data = a.allocate(num);
// or
// T *raw_data = a.allocate(num);
Later, when you actually construct the elements (using placement new, as you said), you'll finally get a meaningful pointer of type T *, but as long as the memory is raw, using T * makes little sense (although it is not an error).
Unless your T has some exotic alignment requirements, the memory returned by the above allocation functions will be properly aligned.
You might actually want to take a look at the memory utilities provided by C++ standard library: std::allocator<> with allocate and construct methods, and algorithms as uninitialized_fill etc. instead or trying to reinvent the wheel.
|
2,383,109 | 2,389,350 | Passing c++ map data to c# | I have a map (enum, vector< double >) in c++ code that I want to access from a c# application. This is legacy code, so I'm limited to using COM objects to pass information. Currently we pass in one enum at a time to c++, and get back one vector at a time as a SAFEARRAY.
I tried passing in a SAFEARRAY of enums, and returning a SAFEARRAY of SAFEARRAYs of doubles. In c#, my SAFEARRAY of SAFEARRAYs becomes a multi-dimension array, where I really want a jagged array.
Is there a way to use SAFEARRAYs to produce a jagged array in c#?
Are they other ways I could use to pass the vectors from the map to c#?
| I found how to do it. Instead of using a SAFEARRAY of SAFEARRAYs, I use a SAFEARRAY of VARIANTs. I turn each vector of doubles into a SAFEARRAY, convert the SAFEARRAY to a VARIANT, and then put the VARIANT into a SAFEARRAY that I return to c#. It produces the jagged array that I want.
|
2,383,334 | 2,383,386 | Find out the number of digits of min/max values of an integral type at compile time | Is there a way to find out the number of digits of min/max values of an integral type at compile time so that it's suitable to be placed as a template parameter?
Ideally, there will be an existing solution in, for example, Boost MPL. Failing that I'm looking for some pointers for a hand-coded solution.
| Is this what you are looking for?
std::numeric_limits<T>::digits10
Number of digits (in decimal base) that can be represented without change.
|
2,383,377 | 2,383,430 | find an item in a stl set in c++ | I am trying to find an author in a set, and i am having problems doing so.
in the library.cpp is where i am adding the information from main()
#include "Library.h"
#include "book.h"
#include "cd.h"
#include "dvd.h"
#include <iostream>
// general functions
ItemSet allBooks;
ItemSet allCDS;
ItemSet allDVDs;
ItemSetMap allBooksByAuthor;
ItemSetMap allmoviesByDirector;
ItemSetMap allmoviesByActor;
ItemSetMap allMusicByBand;
ItemSetMap allMusicByMusician;
const Item* Library::addBook(const string& title, const string& author, const int nPages)
{
ItemSet* obj = new ItemSet();
Book* item = new Book(title,author,nPages);
allBooks.insert(item); // add to set of all books
obj->insert(item);
allBooksByAuthor[author] = obj;
return item;
}
const ItemSet* Library::booksByAuthor(const string& author) const
{
return allBooksByAuthor[author];
}
I want to be able to return all the books by a particular author. Right now i am adding them by
allBooksByAuthor[author] = obj;
it does work. However,
it is a problem since its treating an author of two different books as a duplicate.
so, it will only return one book.
What can i do.. keep in mind i cannot change the function or the sets. so, any const must stay... but can make a new set.
| How about checking to see whether the author is in allBooksByAuthor before inserting them?
allBooksByAuthor[author] = obj;
will replace the ItemSet* which is already in there. So, your ItemSet will only ever have one Item* in it. How about something more like
ItemSetMap::iterator authorsBooks = allBooksByAuthor.find(author);
if(authorsBooks != allBooksByAuthor.end())
{
authorsBooks->second->insert(item);
}
else
{
allBooksByAuthor.insert(make_pair(author, obj));
}
That way, you'll add the new Item to the existing ItemSet rather than always creating a fresh one with one item.
I would also point out that by having your ItemSet containing sets of Item* rather than Item, it's only going to make sure that you're not holding the same pointer in there. You could still have identical Items in your ItemSet. You'll need to either make it hold Items directly (which won't work in this case because the Items pointed to are actually subclasses of Item) or give it a custom comparator if you want to guarantee that it won't contain duplicate Items.
|
2,383,438 | 2,383,474 | How do I return a char* array from a clr assembly? | I have a simple managed C++ assembly which I am providing unmanaged wrappers for some static methods I have in a C# assembly. One of these methods returns a string which I have converted to a "const char*" type in the C++ assembly. The trouble I am having is that when I load this dll from an unmanaged source, I get bad data back in the pointer. What can I do about this? I have simplified my testcase down to this:
managed assembly (Test.dll compiled with /clr; full code follows):
extern "C" {
__declspec(dllexport) const char* GetValue(const char* s) {
return s;
}
}
unmanaged console win32 app:
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
typedef const char* (*GetValueFunc)(const char* s);
int _tmain(int argc, _TCHAR* argv[]) {
wprintf(L"Hello from unmanaged code\n");
HMODULE hDll = LoadLibrary(L"Test.dll");
if (!hDll)
return GetLastError();
wprintf(L"library found and loaded\n");
GetValueFunc getValue = (GetValueFunc)GetProcAddress(hDll, "GetValue");
if(!getValue)
return GetLastError();
wprintf(L"%s\n", getValue("asdf"));
return 0;
}
I get the first two lines just fine, but the third line that comes out is garbage. It also doesn't matter if I make the dll have "#pragma unmanaged" at the top of the cpp file or not (same results).
| wprintf with a %s format specifier will interpret your first parameter as a "const wchar_t*", while you're passing a "const char*" to it. Try to use wchar_t in your GetValue function.
|
2,383,520 | 2,383,566 | On Mac OS X in C++ on a 64-bit CPU, is there a type that is 64 bits? | I can't use "long long"; what should I be using?
| Assuming Snow Leopard (Mac OS X 10.6.2 - Intel), then 'long' is 64-bits with the default compiler.
Specify 'g++ -m64' and it will likely be 64-bits on earlier versions too.
1 = sizeof(char)
1 = sizeof(unsigned char)
2 = sizeof(short)
2 = sizeof(unsigned short)
4 = sizeof(int)
4 = sizeof(unsigned int)
8 = sizeof(long)
8 = sizeof(unsigned long)
4 = sizeof(float)
8 = sizeof(double)
16 = sizeof(long double)
8 = sizeof(size_t)
8 = sizeof(ptrdiff_t)
8 = sizeof(time_t)
8 = sizeof(void *)
8 = sizeof(char *)
8 = sizeof(short *)
8 = sizeof(int *)
8 = sizeof(long *)
8 = sizeof(float *)
8 = sizeof(double *)
8 = sizeof(int (*)(void))
8 = sizeof(double (*)(void))
8 = sizeof(char *(*)(void))
Tested with:
i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646) (dot 1)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Compiling with GCC 4.7.1 on Mac OS X 10.7.5 with option -std=c99, the output from the program is more extensive. Thanks to apalopohapa for pointing out the oversight that long long etc were missing from the original.
1 = sizeof(char)
1 = sizeof(unsigned char)
2 = sizeof(short)
2 = sizeof(unsigned short)
4 = sizeof(int)
4 = sizeof(unsigned int)
8 = sizeof(long)
8 = sizeof(unsigned long)
4 = sizeof(float)
8 = sizeof(double)
16 = sizeof(long double)
8 = sizeof(size_t)
8 = sizeof(ptrdiff_t)
8 = sizeof(time_t)
8 = sizeof(long long)
8 = sizeof(unsigned long long)
8 = sizeof(uintmax_t)
1 = sizeof(int8_t)
2 = sizeof(int16_t)
4 = sizeof(int32_t)
8 = sizeof(int64_t)
1 = sizeof(int_least8_t)
2 = sizeof(int_least16_t)
4 = sizeof(int_least32_t)
8 = sizeof(int_least64_t)
1 = sizeof(int_fast8_t)
2 = sizeof(int_fast16_t)
4 = sizeof(int_fast32_t)
8 = sizeof(int_fast64_t)
8 = sizeof(uintptr_t)
8 = sizeof(void *)
8 = sizeof(char *)
8 = sizeof(short *)
8 = sizeof(int *)
8 = sizeof(long *)
8 = sizeof(float *)
8 = sizeof(double *)
8 = sizeof(int (*)(void))
8 = sizeof(double (*)(void))
8 = sizeof(char *(*)(void))
1 = sizeof(struct { char a; })
2 = sizeof(struct { short a; })
4 = sizeof(struct { int a; })
8 = sizeof(struct { long a; })
4 = sizeof(struct { float a; })
8 = sizeof(struct { double a; })
16 = sizeof(struct { char a; double b; })
16 = sizeof(struct { short a; double b; })
16 = sizeof(struct { long a; double b; })
4 = sizeof(struct { char a; char b; short c; })
16 = sizeof(struct { char a; char b; long c; })
4 = sizeof(struct { short a; short b; })
6 = sizeof(struct { char a[3]; char b[3]; })
8 = sizeof(struct { char a[3]; char b[3]; short c; })
16 = sizeof(struct { long double a; })
32 = sizeof(struct { char a; long double b; })
16 = sizeof(struct { char a; long long b; })
16 = sizeof(struct { char a; uintmax_t b; })
|
2,383,554 | 2,383,582 | A combined function for fprintf and write in c/c++ | In C/C++, there is a 'write() function which let me write to either file or a socket, I just pass in the file descriptor accordingly). And there is a fprintf() which allow me to do fprintf (myFile, "hello %d", name); but it only works for file.
Is there any api which allows me to do both?
i.e. able to let me do print formatting and able to switch between writing to file or socket?
Thank you.
| You can use sprintf or snprintf to print to a char * buffer, and then use write. To get a file descriptor from a FILE * variable, you can use fileno. There is no portable way to go from a file descriptor to a FILE *, though: you can portably to use fdopen to associate a FILE * with a valid file descriptor.
In addition, the latest POSIX standard specifies dprintf, but the GNU libc dprintf man page has this to say:
These functions are GNU extensions, not in C or POSIX. Clearly, the
names were badly chosen. Many systems (like MacOS) have incompatible
functions called dprintf(), usually some debugging version of printf(),
perhaps with a prototype like
void dprintf (int level, const char *format, ...);
where the first parameter is a debugging level (and output is to
stderr). Moreover, dprintf() (or DPRINTF) is also a popular macro name
for a debugging printf. So, probably, it is better to avoid this function in programs intended to be portable.
Of course, the libc manual page is not updated with the latest standard in mind, but you still have to be careful with using dprintf, since you might get something you don't want. :-)
|
2,383,622 | 2,383,636 | Indexing my while loop with count parameter in an array | My function takes an array of ifstream ofjects and the number of ifstream objects as seen below:
void MergeAndDisplay(ifstream files[], size_t count)
My problem is I want to use a while loop to read from the file(s) as long as one of them is open. When I get to eof, I close the file. So I thought I could do something like
int fileNum = 0;
while(files[fileNum].is_open() || something here) {
//do stuff
}
But I am not really sure how to put the correct amount of parameters in my while loop...
| You will have to compute the logic of "is any file in this set open" separately. I suggest making it its own function so that the while loop can be clean and natural, e.g.
bool isAnyOpen(ifstream files[], size_t count) {
for (size_t i = 0; i < count; ++i) {
if (files[i].is_open()) return true;
}
return false;
}
Then you can write
while(isAnyOpen(files, count)) {
// Your code here
}
Edit: This is a more general case solution than what R Samuel Klatchko posted. If your problem is as simple as wanting to just read all the data out of all the files, then use his method since it is more direct.
|
2,383,699 | 2,383,722 | error C2593: 'operator +' is ambiguous | If I have the following files, I get this error (c2593 in VC9).
If I un-comment the prototype in main.cpp, the error disappears. I need to maintain the same functionality while keeping the class out of main.cpp. How can I do that?
Thanks.
main.cpp:
#include "number.h"
//const Number operator + (const Number & lhs, const Number & rhs);
int main(void)
{
Number n1(2); // n1 = 2
Number n2(9,3); // n2 = 3
Number n3 = n1+n2; // n3 = 5
}
number.h:
struct Number
{
int num;
Number(int n=0,int d=1) {num = n/d;}
operator int() {return num;}
operator double() {return num*1.0;}
};
number.cpp:
#include "Number.h"
const Number operator + (const Number & lhs, const Number & rhs)
{
Number tmp;
tmp.num = lhs.num + rhs.num;
return tmp;
}
| You never declare operator + in number.h, you only define it in number.cpp - therefore, when you include number.h in main.cpp, it doesn't know where to go to find operator +.
You must put the declaration of operator + in number.h, outside of the class, then define it in number.cpp
|
2,384,020 | 2,384,234 | What is the purpose of Windows style flags like WS_TILED and WS_ICONIC that are just renaming of others? (Windows/C++) | I was looking at the various windows styles flags, and I noticed that a few flags are defined as such:
#define WS_TILED WS_OVERLAPPED
#define WS_ICONIC WS_MINIMIZE
#define WS_SIZEBOX WS_THICKFRAME
#define WS_TILEDWINDOW WS_OVERLAPPEDWINDOW
What is the purpose of defining new flags that are literally identical to other flags?
| Its purpose is backwards compatibility. WS_TILED and WS_ICONIC probably date back to Windows version 1.
One of Microsoft's great burdens, once they put a #define or function in an SDK header file, they can never delete it again.
|
2,384,095 | 2,384,106 | c++ visual studio 2008 issue with two projects in one solution | I have a solution created using visual studio 2008 named, "Solution", and i have two projects in that solution, project "A" and project "B". when i do a thing like below it shows fatal errors in the bottom. I have given in project A->properties->Additional include Directries as ../B
project B
B.h
#include <iostream>
using namespace std;
class B
{
public:
B();
~B();
};
B.cpp
#include "B.h"
B::B()
{
}
B::~B()
{
}
project A
A.h
#include <iostream>
using namespace std;
class A
{
public:
A();
~A();
};
A.cpp
#include "A.h"
#include "B.h"
A::A()
{
B b;
}
A::~A()
{
}
Main.cpp in project A
#include "B.h"
int main()
{
B b;
system("pause");
}
when i run it says
Error 3 fatal error LNK1120: 2 unresolved externals H:\Sol\Debug\A.exe
Error 2 error LNK2001: unresolved external symbol "public: __thiscall B::B(void)" (??0B@@QAE@XZ) A.obj
Error 1 error LNK2001: unresolved external symbol "public: __thiscall B::~B(void)" (??1B@@QAE@XZ) A.obj
| It doesn't look like you are exporting class B out of project B. So project A sees the declaration of class B but can't find its implementation. What does project B build?
|
2,384,107 | 2,384,187 | How does this template magic determine array parameter size? | In the following code
#include<iostream>
template<typename T,size_t N>
void cal_size(T (&a)[N])
{
std::cout<<"size of array is: "<<N<<std::endl;
}
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1};
cal_size(a);
cal_size(b);
}
As expected the size of both the arrays gets printed. But how does N automatically gets initialized to the correct value of the array-size (arrays are being passed by reference)? How is the above code working?
| N does not get "initialized" to anything. It is not a variable. It is not an object. N is a compile-time constant. N only exists during compilation. The value of N as well as the actual T is determined by the process called template argument deduction. Both T and N are deduced from the actual type of the argument you pass to your template function.
In the first call the argument type is int[6], so the compiler deduces that T == int and N == 6, generates a separate function for that and calls it. Let's name it cal_size_int_6
void cal_size_int_6(int (&a)[6])
{
std::cout << "size of array is: " << 6 << std::endl;
}
Note that there's no T and no N in this function anymore. Both were replaced by their actual deduced values at compile time.
In the first call the argument type is int[1], so the compiler deduces that T == int and N == 1, generates a separate function for that as well and calls it. Let's name it cal_size_int_1
void cal_size_int_1(int (&a)[1])
{
std::cout << "size of array is: " << 1 << std::endl;
}
Same thing here.
Your main essentially translates into
int main()
{
int a[]={1,2,3,4,5,6};
int b[]={1};
cal_size_int_6(a);
cal_size_int_1(b);
}
In other words, your cal_size template gives birth to two different functions (so called specializations of the original template), each with different values of N (and T) hardcoded into the body. That's how templates work in C++.
|
2,384,137 | 2,384,154 | Is the following std::vector code valid? | std::vector<Foo> vec;
Foo foo(...);
assert(vec.size() == 0);
vec.reserve(100); // I've reserved 100 elems
vec[50] = foo; // but I haven't initialized any of them
// so am I assigning into uninitialized memory?
Is the above code safe?
| It's not valid. The vector has no elements, so you cannot access any element of them. You just reserved space for 100 elements (which means that it's guaranteed that no reallocation happens until over 100 elements have been inserted).
The fact is that you cannot resize the vector without also initializing the elements (even if just default initializing).
|
2,384,276 | 2,384,465 | Backslash in the end of comment lines in C/C++ | Does your editor/ide highlight that a++; in this C/C++ code as part of a comment?
int a=1;
//some comment \
a++;
printf("%d\n",a);
And what about this?
int a=1;
//some comment ??/
a++;
printf("%d\n",a);
| emacs 22.3.1: No to both, sadly
|
2,384,360 | 2,384,365 | How can I initialize a reference attribute in my class | I have a class which has a private attribute which is a reference to another class:
class A {
public:
A();
A(B& anotherB);
private:
B& bRef;
}
In my A(B& anotherB), I can do this:
A::A(B& anotherB)
: bRef(anotherB) {
}
But what about A()? I tried this:
A::A()
: bRef(B()) {}
But I get this error 'error: invalid initialization of non-const reference of type ‘B&’ from a temporary of type ‘B’.
How can I call initialize B reference in A with the default constructor of B?
Thank you.
| You have to have a real instance to initialize it to. Saying : bRef(B()) creates a temporary which is immediately destroyed, thus your reference would be to an object that no longer exists, thus the compiler error.
You don't need to initialize it unless you're making some decision based on it not being initialized. In that case you can have a bool initialized; member that you use to keep track of the state.
If you want to initialize it to something like NULL, use a pointer instead.
|
2,384,405 | 2,387,502 | What can cause Phong specular shading to produce gamut overflows? | I am currently implementing a basic raytracer in c++. Works pretty well so far, matte materials (with ambient and diffuse brdf) work as expected so far.
Adding specular highlights would result in the full Phong Model and that's exactly what i tried to do.
Unfortunately, i encounter gamut overflow, with all kinds of values for the specular reflection constant ks and the exponent. Here are some examples.
// Sphere material definition:
ka = 0.9;
kd = 1.0;
ks = 0.3;
exp = 1.0;
color = rgb(1.0, 1.0, 0.98);
image: http://dl.dropbox.com/u/614366/cornell_1.png
// Sphere material definition:
ka = 0.9;
kd = 1.0;
ks = 0.3;
exp = 20.0; // only changed exp
color = rgb(1.0, 1.0, 0.98);
image: http://dl.dropbox.com/u/614366/cornell_2.png
// Sphere material definition:
ka = 0.9;
kd = 1.0;
ks = 0.1; // only changes here
exp = 0.1; // and here
color = rgb(1.0, 1.0, 0.98);
image: http://dl.dropbox.com/u/614366/cornell_3.png
and here are some relevant excerpts of the code:
in raycast.cpp
namespace {
const float floatmax = std::numeric_limits<float>::max();
}
rgb
RayCast::trace ( const Ray& ray ) const
{
HitRecord rec(scene_ptr_);
float tmax = floatmax;
float tmin = 0.0;
if ( scene_ptr_->shapes.hit(ray,tmin,tmax,rec) )
{
rec.ray = ray;
return rec.material_ptr->shade(rec);
}
return scene_ptr_->bgcolor;
}
in phong.cpp
rgb
Phong::shade ( HitRecord& hitrec ) const
{
Vector wo = - hitrec.ray.dir();
rgb L = ambient_brdf_ptr_->rho(hitrec,wo) *
hitrec.scene_ptr->ambient_ptr->L(hitrec);
int num_lights = hitrec.scene_ptr->lights.size();
for (int i = 0; i < num_lights; ++i)
{
Vector wi = hitrec.scene_ptr->lights[i]->get_direction(hitrec);
float ndotwi = dot(hitrec.normal, wi);
if ( ndotwi > 0.0 )
{
L += ( diffuse_brdf_ptr_->f (hitrec, wo, wi) +
specular_brdf_ptr_->f(hitrec, wo, wi)
) * hitrec.scene_ptr->lights[i]->L(hitrec) * ndotwi;
}
}
return L;
}
in specular.cpp
namespace {
const rgb black(0.0,0.0,0.0);
}
rgb
Specular::f ( const HitRecord& hitrec, const Vector& wo, const Vector& wi ) const
{
rgb L(0,0,0);
float ndotwi = dot(hitrec.normal, wi);
Vector r = -wi + 2.0 * hitrec.normal * ndotwi;
float rdotwo = dot(r, wo);
// reflection detected
if ( rdotwo > 0.0 )
L = ks_ * pow(rdotwo, exp_);
return L;
}
rgb
Specular::rho ( const HitRecord& hitrec, const Vector& wo ) const
{
return black;
}
in sphere.cpp
bool
Sphere::hit ( const Ray& ray, interval_t tmin, interval_t tmax, HitRecord& hitrec ) const
{
Vector org = ray.origin() - center_;
Vector dir = ray.dir();
float a = dot(dir, dir);
float b = dot(dir, org) * 2;
float c = dot(org, org) - pow(radius_, 2);
float discriminant = pow(b,2) - 4*a*c;
if ( discriminant > 0 )
{
discriminant = sqrt(discriminant);
double t = ( -b - discriminant ) / ( 2*a );
if ( t < tmin )
t = ( -b + discriminant ) / ( 2*a );
if ( t > tmin and t < tmax )
{
// hit detected
hitrec.t = t;
hitrec.hit = true;
hitrec.normal = unify( t*ray.dir() + org );
hitrec.material_ptr = material_ptr_;
hitrec.hitpoint = ray.origin() + t * ray.dir();
hitrec.ray = ray;
return true;
}
}
return false;
}
do you have ideas where the error could be caused? what are possible factors that lead to such results?
thanks in advance,
patrick.
| The solution to the problem is that you have to unify the wo vector (in Phong::shade).
|
2,384,558 | 2,384,579 | C++ inline class definition and object initialisation | I've just come across the following code:
#include <iostream>
static class Foo
{
public:
Foo()
{
std::cout << "HELLO" << std::endl;
}
void foo()
{
std::cout << "in foo" << std::endl;
}
}
blah;
int main()
{
std::cout << "exiting" << std::endl;
blah.foo();
return 0;
}
I haven't seen the above method of definining a variable before - the class definition is done inline with the variable definition. It reminds me of anonymous classes in Java. What is this called, and is it in the C++ standard?
Thanks
Taras
| It's quite standard to define a class (or struct, perfectly equivalent except that the default is public instead of private) and declare a variable of its type (or pointer to such a variable, etc) -- it was OK in C (with struct, but as I already mentioned C++'s class, save for public vs private, is the same thing as struct) and C++ mostly maintains upwards compatibility with (ISO-1989) C. Never heard it called by any special name.
|
2,384,562 | 2,384,611 | Double UDP socket binding in Linux | In C++, when I run (red alert! pseudo-code)
bind(s1, <local address:port1234>)
bind(s2, <local address:port1234>)
on two different UDP sockets (s1 and s2 each created with a call to socket()) I get problems. In Linux (Ubuntu), the double binding seems to be fine. In Windows, however, the double binding fails, and the call to bind() the second time for the same address returns != 0.
I want to get the behavior I have on Windows on my Linux machine. Are there some settings I can work to get a "port busy" on Linux?
| Please see bind and setsockopt. Unless you have invoked setsockopt with SO_REUSEADDR, then your invocation of bind with the same address should result in failure with EADDRINUSE.
|
2,384,637 | 2,384,668 | const reference to temporary and copying - C++ | Please consider the following code,
struct foo
{
foo()
{
std::cout << "Constructing!" << std::endl;
}
foo(const foo& f)
{
std::cout << "Copy constructing!" << std::endl;
}
~foo()
{
std::cout << "Destructing.." << std::endl;
}
};
foo get()
{
foo f;
return f;
}
int main()
{
const foo& f = get();
std::cout << "before return" << std::endl;
return 0;
}
Output on MSVC
Constructing!
Copy constructing!
Destructing..
before return
Destructing..
Output of GCC
Constructing!
before return
Destructing..
The result which comes on MSVC looks incorrect.
Questions
AFAIK, GCC produces the correct result here. Why MSVC is giving different results and why it is doing copy construction?
const foo& f = get() and const foo f = get() produces same output because of return value optimization. In this case, which way of writing should be preferred?
Any thoughts..
| Your MSVC build has no optimizations on. Turn them on, you'll get identical output for both.
GCC is merely performing, by default, RVO on your temporary. It's basically doing:
const foo& f = foo();
MSVC is not. It's making the foo in the function, copying it to the outside the function (ergo the copy-constructor call), destructing the inner foo, then binds the reference.
Both outputs are correct. RVO is one instance where the standard explicitly allows the observable behavior of the program to change.
|
2,384,739 | 2,384,914 | Template class, static function compile error c++ | I have the following function defined inside my linked list class. The declaration in the header file looks like this:
template <typename T>
class RingBuffer
{
...//stuff
static BLink * NewLink (const T&); // allocator
};
BLink is a "link" class within the RingBuffer class. The following implementation code:
template <typename T>
RingBuffer<T>::BLink * RingBuffer<T>::NewLink( const T& t ) // this is line 114
{
// create a new link in linked list
....
....
}
Is giving me this compile error:
./ringbuff.cpp:114: error: expected constructor, destructor, or type conversion before â*â token
I am stumped as to why it it needs an expected constructor, destructor, or type conversion before the return value.
| The problem here is that you are referring to a nested dependent type name (i.e. BLink is nested inside RingBuffer which is dependent on a template parameter)
You need to help your compiler a little in this case by stating that RingBuffer<T>::BLink is an actual type name. You do this by using the typename keyword.
template <typename T>
typename RingBuffer<T>::BLink * RingBuffer<T>::NewLink(const T& t)
{
// ...
}
Explanation:
The compiler cannot know if RingBuffer<T>::BLink is a type name or a static member until the template parameter T is known. When the compiler parses your function template T is not known and the rule to solve the ambiguity is to default to "this is not a type name".
Another short example (blatantly copied from Scott Meyers' Effective C++):
template<typename C>
void print2nd(const C& container)
{
C::const_iterator * x;
…
}
This maybe illustrates the problem a little better as it's more compact. As already said it's not clear for the parser whether C::const_iterator is a type name or a static data member as it doesn't know what C is when it parses this part of the code (it may know at a later point in time when the template is actually instantiated). So to ease the compiler implementers' lives this ambiguity is resolved to "not a type name" and if the programmer wants to use a type name which is nested inside anything that is dependent on a template parameter he/she has to use the typename keyword in front of the name to let the compiler know that it should be treated as a type name.
Unfortunately there is an exception to that rule regarding nested dependent type names when using them inside a base class list or the base class identifier in a member initialization list.
template<typename T>
struct Base {
struct Nested {
Nested(int) {}
};
};
template<typename T>
struct Derived : public Base<T>::Nested { // typename not allowed here
Derived(int i)
: Base<T>::Nested(i) // nor here
{}
};
Btw: You should set your console client's charset to UTF-8, so you get ‘*’ instead of â*â.
|
2,384,761 | 2,384,857 | C++: Cannot instantiate a pointer directly | This is an SDL problem, however I have the strong feeling that the problem I came across is not related to SDL, but more to C++ / pointers in general.
To make a long story short, this code doesn't work (edited to show what I really did):
player->picture = IMG_Load("player");
SDL_BlitSurface(player->picture, NULL, screen, &pictureLocation);
I see nothing on the screen. However, when I do it like this, it works:
SDL_Surface* picture = IMG_Load("player.png");
player->picture = picture;
SDL_BlitSurface(player->picture, NULL, screen, &pictureLocation);
I can see the little guy just fine.
The real problem is that I cannot instantiate Player::picture directly. Even when I try
picture = IMG_Load("player.png")
in player.cpp, I end up with a nullpointer.
| I am so stupid. Turns out like I forgot the file extension ".png" every time I tried to store the surface in Player::picture, and conveniently remembered to add it every time I stired it in an SDL_Surface declared in main.cpp.
I had the feeling I was overlooking something really simple here, but this is just embarassing. What's a fitting punishment for this?
|
2,384,782 | 2,388,726 | Printf used in unfamiliar fashion | I found this line of code when upgrading a C++ Builder project to RAD Studio 2009:
mProcessLength->Text.printf("%d",mStreamLength);
It doesn't compile in 2009, however what is the intent of this line and what is a better equivalent? Given that mProcessLength->Text is now a wchar_t*.
| I suspect that you are getting these errors:
E2034 Cannot convert 'const char *' to 'const wchar_t *'
E2342 Type mismatch in parameter 'format' (wanted 'const wchar_t *', got 'const char *')
It's the parameters you are passing to printf that are mismatched.
Changing it to:
mProcessLength->Text.printf(L"%d",mStreamLength);
will change your string literal to the correct type.
|
2,384,933 | 2,385,008 | Program configuration data in Unix/Linux | What is recommended way to keep a user configuration data in Unix/Linux?
My programming language is C++. Configuration data will be kept in XML/text/binary format, I have no problem with handling such files. I want to know where can I keep them. For example, in the Windows OS configuration data may be kept in the Registry (old way) or in user application data directory. What about Linux?
I need read/write access to configuration files.
| The concept of the registry is peculiar to Windows, and Microsoft once admitted to it being ill-conceived (see this, this, this, this (see #2), and this).
In Unix and Linux, configuration for system-wide programs is in /etc or maybe an application-specific subdirectory.
Per user configuration data are kept in the user's home directory in a hidden file—in text format—or an application-specific hidden directory in the user's home directory. The proper way to reference the home directory is through the environment variable HOME. Hidden files and directories are created by making . the first character of the name.
Examples for system-wide configuration is /etc/wgetrc and /etc/ssh/. Examples of per-user data are $HOME/.bashrc and $HOME/.mozilla/.
|
2,385,599 | 2,385,772 | Visual C++ Tail Call Optimization | According to answers to that question:
Which, if any, C++ compilers do tail-recursion optimization?
it seems, that compiler should do tail-recursion optimization.
But I've tried proposed options and it seems that compiler can't do this optimization in case of template functions. Could it be fixed somehow?
| I don't use the MS compilers, but GCC can certainly do tail-recursion optimisation for templates. Given this function:
template <typename T>
T f( T t ) {
cout << t << endl;
if ( t == 0 ) {
return t;
}
return f( t - 1 );
}
The code produced is:
5 T f( T t ) {
6 cout << t << endl;
- 0x401362 <main+22>: mov %esi,0x4(%esp)
- 0x401366 <main+26>: movl $0x4740c0,(%esp)
- 0x40136d <main+33>: call 0x448620 <_ZNSolsEi>
- 0x401372 <main+38>: mov %eax,%ebx
7 if ( t == 0 ) {
- 0x4013a5 <main+89>: test %esi,%esi
- 0x4013a7 <main+91>: je 0x4013c8 <main+124>
8 return t;
9 }
10 return f( t - 1 );
- 0x4013a9 <main+93>: dec %esi
- 0x4013aa <main+94>: jmp 0x401362 <main+22>
11 }
You can see that the recursive call has been turned into a jump back to the start of the function. This optimisation is only performed by GCC if the code is compiled with optimisations enabled (-O2 in this case) - perhaps the same is true for MS C++?
|
2,385,673 | 2,386,528 | Setting up cURL library for MSVS | I'm trying to write a simple curl program to retrieve the web page in VC++ 8.0.
#include <stdio.h>
#include <curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
I added the include and library paths to cURL include and lib directory. It complies but when I try to enter debug mode, An unhandled non-continuable STATUS_DLL_NOT_FOUND exception was thrown during process load and code exits with -1073741515 (0xc0000135).
| if you run it outside of debug mode, does it work as expected? or does the same error occur?
if it doesn't work outside of debug mode, your application was not able to locate the dll.
another question, are you tring to compile libcurl from sources along with your project, or are you using it as an external library?
if you are using the sources, you might need to compile the whole solution so that libcurl is compiled as well.
if you are using the external library, try putting the dll in the working directory of your application (it wasn't able to locate it).
|
2,385,690 | 2,386,586 | Sorting only using the less-than operator compared to a trivalue compare function | In C++/STL sorting is done by using only the less-than operator. Altough I have no idea how the sorting algorithms are actually implemented, I assume that the other operations are created implicite:
a > b *equals* b < a == true
a == b *equals* !(a < b) && !(b < a)
Compared to using a trivalue* compare function, like for example Java, is this good for performance, or why was this design decision made?
My assumption is that any trivalue compareto function still has to implement these comparissons in itself, resulting in the same performance.
**by trivalue compare function, I mean a compare function which returns -1, 0 and 1 for less than, equal and higher than*
Update:
It seems a spaceship <=> operator are coming in C++20 so obviously the committee thought there were downsides of using only operator<.
| In a sense the other two are implicit, but more accurate would be to say that a comparison sort doesn't actually need a tri-valued comparator, and C++'s sorts are implemented in a way which doesn't use one in order to minimise the behaviour required of the comparator.
It would be wrong for std::sort to define and exclusively use something like this:
template <typename T, typename Cmp>
int get_tri_value(const T &a, const T &b, Cmp lessthan) {
if (lessthan(a,b)) return -1;
if (lessthan(b,a)) return 1;
return 0;
}
... because you'd end up with an inefficient algorithm in terms of number of calls to lessthan. If your algorithm doesn't do anything useful with the difference between a 1 return and a 0 return, then you've wasted a comparison.
C++ refers to "strict weak orderings". If < is a strict weak ordering, and !(a < b) && !(b < a), it doesn't necessarily follow that a == b. They're just "in the same place" in the ordering, and !(a < b) && !(b < a) is an equivalence relation. So the comparator required by sort orders equivalence classes of objects, it doesn't provide a total order.
The only difference it makes is what you say when !(a < b). For a strict total order, you would deduce b <= a, read "less than or equal to". For a strict weak order, you can't define b <= a to mean b < a || b == a and have this be true. C++ is pedantic about this, and since it allows operator overloading it pretty much has to be, since people overloading operators need the jargon in order to tell users of their code what they can expect in terms of how the operators relate. Java does talk about the comparator and the hashCode being consistent with equals, which is all you need. C++ has to deal with <, >, ==, <=, >=, the post-condition of assignment, and so on.
C++ takes quite a pure mathematical approach to this in the API, so everything is defined in terms of the single binary relation. Java is friendlier in some respects, and prefers three-way comparisons where the definition of the fundamental unit (the comparison) is a bit more complex, but the logic leading from it is simpler. It also means the sort algorithm gets more information per comparison, which occasionally is useful. For an example, see the "Dutch flag" quicksort optimisation, which is a benefit when there are a lot of "in the same place" duplicates in the data.
In that case, a three-values comparator is a speed gain. But C++ uses a consistent definition of a comparator for sort and also for set and map, lower_bound and so on, which barely benefit from a three-value comparator (maybe save one comparison, maybe not). I'd guess they decided not to complicate their nice, general interface in the interests of specific or limited potential efficiency gains.
|
2,385,698 | 2,385,974 | Why does the following code not generate a warning in MSVC | I have a section of code that can be summarised as follows;
void MyFunc()
{
int x;
'
'
x;
'
'
}
I would have thought that simply referencing a variable, without modifying it in anyway or using its value in anyway should generate a warning. In VS2003 it does neither, and it I need lint to pick it up.
I realise it doesn't effect execution, but since it is a piece of code that does nothing, and the programmer doubtless intended to do something, why is it not flagged?
Similarly would you expect x = x to be a warning?
Edit: Modified question, as this constitutes a good candidate for a warning, but is not an error. Replies suggest this is handled better with other compilers. Will try out VS2008 later and post result.
| You need to use a better compiler :-) Compiled with the -Wall and -pedantic flags, the GCC C++ compiler given this code:
int main() {
int x = 0;
x;
}
produces this diagnostic:
ma.cpp:3: warning: statement has no effect
|
2,385,744 | 2,385,769 | Simplest way to validate a GPS string in C++? | I have some MET data I want to validate which would look something like these:
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
I've tried a simple sscanf, but that failed:
int _tmain(int argc, _TCHAR* argv[])
{
char validBuffer[] = {"N51374114W1160437"};
char invalidBuffer[] = {"bad data\n"};
char emptyBuffer[] = {""};
char ns = ' ';
char ew = ' ';
int northing = -999;
int easting = -999;
int paramsConverted = sscanf_s(validBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", validBuffer, paramsConverted, ns, northing, ew, easting);
paramsConverted = sscanf_s(invalidBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", invalidBuffer, paramsConverted, ns, northing, ew, easting);
paramsConverted = sscanf_s(validBuffer, "%c%d%c%d", &ns, &northing, &ew, &easting);
printf("Converted \"%s\"; Found %d params [%c,%d,%c,%d]\n", emptyBuffer, paramsConverted, ns, northing, ew, easting);
getchar();
return 0;
}
gives me:
Converted "N51374114W1160437"; Found 2 params [N,-999,",-1024]
Converted "bad data
"; Found 1 params [b,-999,",-1024]
Converted ""; Found 2 params [N,-999,",-1024]
I'd rather not use any external libraries if at all possible, so is there a nice simple way of doing this without parsing it one character at a time?
| How about using Regular expressions from TR1?
|
2,385,913 | 3,244,508 | How to set timeout in mysql c++ connector | I am using c++ connector to connect to MySQL server. When server is offline or in sleep,the statement execute method takes a while to detect the connection problem.
Is there a method or variable to control the waiting timeout period in client?
Regards
Devara Gudda
| You can use the mysql_options function to set the client timeout. Full details here... http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html
|
2,386,067 | 2,432,260 | C++ function calling from C# application. Attempted to read or write protected memory | The problem below is ralated to my previous question
Converting static link library to dynamic dll
My first step was to develop a dll, that was done. (Thanks John Knoeller prakash. Your input was very helpful)
Now when i call the function in the dll from my c# application i get the error
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Here is the C++ definition
extern "C" DEMO2_API void Decompress(char* inp_buff, unsigned short*
inp_len, char* buffer_decomp,unsigned *output_len,unsigned short* errorCode);
My C# Converstion p/Involke
private static extern void Decompress(
byte[] inp_buff,
ref ushort inp_len,
byte[] buffer_decomp,
ref int output_len,
ref ushort errorCode
);
And I am calling it as below
byte[] dst = new byte[2048];
int outlen = 2048;
ushort errorCode = 0;
Decompress(src, (ushort )src.Length, dst, ref outlen,ref errorCode);
return dst;
What is wrong?
| The 4th parameter need to be passed using out mode instead of ref. That solved the problem.
|
2,386,161 | 2,386,233 | Why autoconf isn't detecting boost properly? | I am using autoconf to detect boost libraries, with the support of the autoconf-archive macros and they work fine with system-wide boost libraries, but fail if I manually compile boost in my home directory:
sb@stephane:~/devel/spectra2$ ./configure --with-boost=/home/sb/local/
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking for style of include used by make... GNU
checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking dependency style of gcc... gcc3
checking for library containing strerror... none required
checking for g++... g++
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking dependency style of g++... gcc3
checking for boostlib >= 1.31.0... yes
checking whether the Boost::Program_Options library is available... yes
checking for exit in -lboost_program_options... yes
checking whether the Boost::Filesystem library is available... yes
checking for exit in -lboost_filesystem... no
checking for exit in -lboost_filesystem... (cached) no
checking for exit in -lboost_filesystem... (cached) no
configure: error: Could not link against boost_filesystem !
As you can see, it detects some libraries fine, but it fails with boost-filesystem. These are the contents of ~/local/lib:
sb@stephane:~$ ls -1 /home/sb/local/lib/
libboost_filesystem.a
libboost_filesystem.so
libboost_filesystem.so.1.42.0
libboost_program_options.a
libboost_program_options.so
libboost_program_options.so.1.42.0
libboost_system.a
libboost_system.so
libboost_system.so.1.42.0
libboost_thread.a
libboost_thread.so
libboost_thread.so.1.42.0
So the library is there. I tried with both boost-1.39 and boost-1.42 with no different result, any idea why is this happening? Did I forget about something?
| Since boost-1.39 libboost_filesystem depends on libboost_system. Before 1.39 you could only link to boost_filesystem, in later versions you have to link to both of them.
Maybe it has something to do with your error.
|
2,386,224 | 2,386,262 | c++ transform with pair get Segmentation fault | This code works:
class Test
{
public:
Test(string name) : _name(name) {};
bool operator()() { cout << "hello " << _name << endl; return true; }
string name() { return _name; }
private:
string _name;
};
pair<string, bool>
inline execute_test(Test* t) {
return pair<string, bool>(t->name(), (*t)());
}
int main()
{
vector<Test*> tests;
vector<pair<string, bool> > results;
tests.push_back(new Test("Test1"));
tests.push_back(new Test("Test2"));
for (unsigned int i=0; i < tests.size(); ++i)
results.push_back(execute_test(tests[i]));
}
now I want to use trasform instead of the for cicle:
transform(tests.begin(), tests.end(),
results.begin(),
execute_test);
but I got a Segmentation Fault. Where is the problem?
| That is because transform is expecting results object to have the required memory allocated i.e. it is expecting results.size() is atleast as big as tests.size(). If you want to push_back operation to be performed on the results then you should use std::back_inserter(results) as the third argument. Otherwise, when transform uses the * output iterator you passed, it will be a invalid memory location and will result in a segmentation fault.
|
2,386,231 | 2,386,279 | Under what circumstances must I provide, assignment operator, copy constructor and destructor for my C++ class? | Say I've got a class where the sole data member is something like std::string or std::vector. Do I need to provide a Copy Constructor, Destructor and Assignment Operator?
| In case your class contains only vector/string objects as its data members, you don't need to implement these. The C++ STL classes (like vector, string) have their own copy ctor, overloaded assignment operator and destructor.
But in case if your class allocates memory dynamically in the constructor then a naive shallow copy will lead to trouble. In that case you'll have to implement copy ctor, overloaded assignment operator and destructor.
|
2,386,492 | 2,386,535 | How to remove smart pointers from a cache when there are no more references? | I've been trying to use smart pointers to upgrade an existing app, and I'm trying to overcome a puzzle. In my app I have a cache of objects, for example lets call them books. Now this cache of books are requested by ID and if they're in the cache they are returned, if not the object is requested from an external system (slow operation) and added to the cache. Once in the cache many windows can be opened in the app, each of these windows can take a reference to the book. In the previous version of the app the programmer had to maintain AddRef and Release, when every window using the Book object was closed, the final Release (on the cache manager) would remove the object from the cache and delete the object.
You may have spotted the weak link in the chain here, it is of course the programmer remembering to call AddRef and Release. Now I have moved to smart pointers (boost::intrusive) I no longer have to worry about calling AddRef and Release. However this leads to a problem, the cache has a reference to the object, so when the final window is closed, the cache is not notified that no-one else is holding a reference.
My first thoughts were to periodically walk the cache and purge objects with a reference count of one. I didn't like this idea, as it was an Order N operation and didn't feel right. I have come up with a callback system, which is better but not fantastic. I have included the code for the callback system, however I was wondering if anyone had a better way of doing this?
class IContainer
{
public:
virtual void FinalReference(BaseObject *in_obj)=0;
};
class BaseObject
{
unsigned int m_ref;
public:
IContainer *m_container;
BaseObject() : m_ref(0),m_container(0)
{
}
void AddRef()
{
++m_ref;
}
void Release()
{
// if we only have one reference left and we have a container
if( 2 == m_ref && 0 != m_container )
{
m_container->FinalReference(this);
}
if( 0 == (--m_ref) )
{
delete this;
}
}
};
class Book : public BaseObject
{
char *m_name;
public:
Book()
{
m_name = new char[30];
sprintf_s(m_name,30,"%07d",rand());
}
~Book()
{
cout << "Deleting book : " << m_name;
delete [] m_name;
}
const char *Name()
{
return m_name;
}
};
class BookList : public IContainer
{
public:
set<BookIPtr> m_books;
void FinalReference(BaseObject *in_obj)
{
set<BookIPtr>::iterator it = m_books.find(BookIPtr((Book*)in_obj));
if( it != m_books.end() )
{
in_obj->m_container = 0;
m_books.erase( it );
}
}
};
namespace boost
{
inline void intrusive_ptr_add_ref(BaseObject *p)
{
// increment reference count of object *p
p->AddRef();
}
inline void intrusive_ptr_release(BaseObject *p)
{
// decrement reference count, and delete object when reference count reaches 0
p->Release();
}
} // namespace boost
Cheers
Rich
| I never used boost::intrusive smart pointers, but if you would use shared_ptr smart pointers, you could use weak_ptr objects for your cache.
Those weak_ptr pointers do not count as a reference when the system decides to free their memory, but can be used to retrieve a shared_ptr as long as the object has not been deleted yet.
|
2,386,552 | 2,976,704 | Error yaml-cpp compile in RAD Studio 2010 | I can't compile yaml-cpp in RAD Studio 2010. I have error in nodeutil.h
template <typename T, typename U>
struct is_same_type {
enum { value = false };
};
template <typename T>
struct is_same_type<T, T> {
enum { value = true };
};
template <typename T, bool check>
struct is_index_type_with_check {
enum { value = false };
};
template <> struct is_index_type_with_check<std::size_t, false>
{ enum { value = true }; }; // line 24
#define MAKE_INDEX_TYPE(Type) \
template <> struct is_index_type_with_check<Type, is_same_type<Type, std::size_t>::value> { enum { value = true }; }
MAKE_INDEX_TYPE(int);
MAKE_INDEX_TYPE(unsigned); // line 30
MAKE_INDEX_TYPE(short);
MAKE_INDEX_TYPE(unsigned short);
MAKE_INDEX_TYPE(long);
MAKE_INDEX_TYPE(unsigned long);
#undef MAKE_INDEX_TYPE
Compiler print:
[BCC32 Error] nodeutil.h(30): E2238 Multiple declaration for 'is_index_type_with_check<unsigned int,0>'
[BCC32 Error] nodeutil.h(24): E2344 Earlier declaration of 'is_index_type_with_check<unsigned int,0>'
I think that all correct - in line 24 I got
is_index_type_with_check<std::size_t, false>,
in line 30 I got
is_index_type_with_check<unsigned, true>.
Two different type.
But if I change line 24 like below, RAD Studio can compile yaml-cpp
template <> struct is_index_type_with_check<std::size_t, true> { enum { value = true }; }; // false -> true
Why?! In line 24 I got
is_index_type_with_check<std::size_t, true>
and in line 30
is_index_type_with_check<unsigned, true>
Two identically type. But all work in RAD Studio and doesn't in MS VS 2008 Express.
| Trying out your code with CodeBlocks, the problems showed exactly vice versa. This means, that my code compiles with
template <> struct is_index_type_with_check<std::size_t, false>
and fails with
template <> struct is_index_type_with_check<std::size_t, true>
in line 24.
The problem seems to be, which types compilers think are the same and which are different. This problem spreads over different phases of the compile process. Look again at your compiler error. The template arguments of is_index_type_with_check are the same for both std::size_t and unsigned. That means, that your compiler thought that std::size_t and unsigned are different types for template argument deduction (is_same_type::value == false), but the type deduction later found std::size_t and unsigned to be of the same type unsigend int and complains with an error.
So to sum up you didn't read your compiler error correctly - MAKE_INDEX_TYPE(unsigned); created an is_index_type_with_check<unsigned int, false>. That type clashed with your template <> struct is_index_type_with_check<std::size_t, false> and the compiler complained.
|
2,386,671 | 2,386,730 | Help with using Xcode | So, I'm using Xcode to program with C++. I want to access the C++ tool but I'm having this problem.
This is what it looks like when opening a new project. Only for me, I don't have the 'Command Line Utility' option at the end.
alt text http://img.skitch.com/20100305-gsab76ef7bkx5ihwwj94cui39t.jpg
How can I get the 'Command Line Utility' option to be available. I need it to access the C++ tool.
Please and thank you!
| If you're on a reasonably current version of Xcode (e.g. 3.2.2) then the selection process is slightly different - you need Application -> Command Line Tool and then select C++ stdc++ from the popup menu.
|
2,386,772 | 2,386,882 | What is the difference between float and double? | I've read about the difference between double precision and single precision. However, in most cases, float and double seem to be interchangeable, i.e. using one or the other does not seem to affect the results. Is this really the case? When are floats and doubles interchangeable? What are the differences between them?
| Huge difference.
As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.
Here's how the number of digits are calculated:
double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits
float has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits
This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.
float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
b += a;
printf("%.7g\n", b); // prints 9.000023
while
double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
b += a;
printf("%.15g\n", b); // prints 8.99999999999996
Also, the maximum value of float is about 3e38, but double is about 1.7e308, so using float can hit "infinity" (i.e. a special floating-point number) much more easily than double for something simple, e.g. computing the factorial of 60.
During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.
Of course, sometimes, even double isn't accurate enough, hence we sometimes have long double[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int or a fraction class.
Furthermore, don't use += to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum. Otherwise, try to implement the Kahan summation algorithm.
[1]: The C and C++ standards do not specify the representation of float, double and long double. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float is indeed a IEEE single-precision floating point number (binary32), and double is a IEEE double-precision floating point number (binary64).
|
2,386,896 | 2,386,948 | Retrieve time from the internet (bypassing PC clock)? | For my MFC/C++ unmanaged time-limited software needs, I'd like to get a GMT/UTC time-stamp from the internet (instead of relying on the PC clock time that can be easily changed).
I already though about parsing the line "Current UTC"... line from http://www.timeanddate.com/worldclock/ (I think port 80 is more likely to be open than others) but I don't know how reliable this URL is...
Please share with me your pros/cons or different ideas on this.
Thanks.
| Looks feasible and this is widely done.
Scraping of timeanddate.com can break if the site decides to change its HTML. Even a slight change in the HTML can break your scraper.
I would suggest you use a web service like earthtools. You'll have to pass the necessary arguments(latitude and longitude etc) in the URL and the response is XML which you can easily parse.
|
2,387,083 | 2,387,089 | Where should you put global constants in a C++ program? | Where would you put global constants in a C++ application? For example would you put them in a class? In a struct?
| I would use a namespace for global constants which are not very strongly associated with a single class. In the latter case, I would put them in that class.
Really global (application-level) constants should be in the application's namespace (provided your application is inside it's own namespace, as it should be). For module-level constants, the module's own namespace is the natural place.
|
2,387,173 | 2,421,178 | Open Source FIX Client Simulator | I want test a FIX gateway for our company and was wondering if anything in opensource already exists that I can use or perhaps leverage to complete this task.
I am currently looking at QuickFix but I am not sure if it has a client that can be use against any standard FIX gateway.
Also links to any learning material that exist on this topic would be appreciated.
Thanks
| QuickFIXengine code comes with couple of examples, see http://www.quickfixengine.org/quickfix/doc/html/examples.html
You probably want tradeclient for sending messages. It is a command line tool that will send FIX messages to server.
You can use the ordermatch example to start up simple FIX server which will cross orders and send ExecutionReports back to your client.
For all example applications you need to provide a config file to startup up. Just follow the instructions at quickfixengine web site, see example config file. Your client will be initiator and server acceptor.
I've been using those example apps heavily for testing especially the ordermatcher, I've updated mine to handle amend orders and separates stock/futures/options symbols and so on.
The tradeclient uses screen logger so you should see all the outgoing and incoming messages on the command line.
|
2,387,386 | 2,387,414 | Using C++ hex and cin | If you have the following code:
cout << hex << 10;
The output is 'a', which means the decimal 10 is converted into its hexadecimal value.
However, in the code below...
int n;
cin >> hex >> n;
cout << n << endl;
When input is 12, the output becomes 18. Can anyone explain the details of the conversion? How did it became a decimal value?
I'm interested in the point where it became an int. If broken down, it would be:
(( cin >> hex ) >> n);
Is this correct?
| The hex manipulator only controls how a value is read - it is always stored using the same internal binary representation. There is no way for a variable to "remember" that it was input in hex.
|
2,387,403 | 2,536,571 | STLport crash (race condition, Darwin only?) | When I run STLport on Darwin I get a strange crash. (Haven't seen it anywhere else than on Mac, but exactly same thing crash on both i686 and PowerPC.) This is what it looks like in gdb:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
[Switching to process 21097]
0x000000010120f47c in stlp_std::__node_alloc_impl::_M_allocate ()
It may be some setting in STLport, I noticed that Mac.h and MacOSX.h seemed far behind on features. I also know that it it must be some type of race condition, since it doesn't occur just by calling this method (implicity called). The crash happens mainly when I push the system, running 10 simultaneous threads that do a lot of string handling.
Other theories I come up with have to do with compiler flags (configure script) and g++ 4.2 bugs (seems like 4.4.3 isn't on Mac yet with Objective-C support, which I need to link with).
HELP!!! :)
Edit: I run unit tests, which do all sorts of things. This problem arise when I start 10 threads that push the system; and it always comes down to std::string::append which eventually boils down to _M_allocate. Since I can't even get a descent dump of the code that's causing the problem, I figure I'm doing something bad. Could it be so since it's trying to execute at instruction pointer 0x000...000? Are dynlibs built as DLLs in Windows with a jump table? Could it perhaps be that such a jump table has been overwritten for some reason? That would probably explain this behavior. (The code is huge, if I run out of other ideas, I'll post a minimum crashing sample here.)
| This problem was caused by an unrelated crash bug, causing memory overwrites leading to an STLport crash in my case.
|
2,387,484 | 2,389,369 | ComCtl32.dll Version 6 with Qt | I'm trying to implement a balloon tip. By following the instructions on this page:
http://msdn.microsoft.com/en-us/library/bb760252%28VS.85%29.aspx
I managed to implement the balloon, but the balloon is not using the appropriate theme under Win7. I read somewhere else that for the balloon to use the right visual style, ComCtl32.dll Version 6 must be used.
http://msdn.microsoft.com/en-us/library/ms997646.aspx
Now, my development platform is Qt. Is there any way to tell Qt to use ComCtl32.dll Version 6? Or am I forced to use Visual Studio?
| I've blogged about this.
|
2,387,647 | 2,387,674 | Exception specification when overriding a virtual function | Consider the following code:
class A
{
public:
virtual void f() throw ( int ) { }
};
class B: public A
{
public:
void f() throw ( int, double ) { }
};
When compiled, it says that derived class B has a looser throw specifier compared to A. What is the importance of this? If we try to exchange their exception specification, such that A::f() throws int and double while B::f() throws only int, the error does not appear.
|
Don't use exception specifications in C++. It's very counter-intuitive compared to, say, Java's ones.
Having a wider specification in the derived class breaks LSP (Liskov Substitution Principle).
To expand on point 2: A's callers expect that only int comes out, but if you use a B (which, because it's publicly derived from A, also means it's usable as an A), suddenly double can come out too, and that would break A's contract (that only int gets thrown).
|
2,387,914 | 2,388,027 | Basic questions about RAII, STL pop, and PIMPL | While reading proggit today, I came upon this comment in a post about how the top places in the Google Ai challenge were taken by C++. User reventlov declares
The biggest problem I have with C++ is that it's waaay too easy to think that you're a "C++ programmer" without really understanding all the things you need to understand to use C++ acceptably well.
You've got to know RAII, and know to use namespaces, and understand proper exception handling (for example, you should be able to explain why the pop() methods in the STL do not return the values they remove). You've got to know which of the three generations of functions in the standard library is the right one. You should be familiar with concepts like PIMPL. You need to understand how the design of the standard library (especially the STL) works. You need to understand how macros interact with namespaces, and why you usually shouldn't use macros in C++, and what you should use instead (usually templates or inlines, rarely a class). You need to know about boost.
I think I'm one of those clueless C++ programmers he mentions. To keep this brief, my questions are
Can you give an example of a typical RAII oversight mistake, e.g. where best practices dictate the use of RAII but programmers have implemented using some other way?
Why doesn't the pop() methods in STL return the value they remove?
I read the Wikipedia entry for PIMPL, didn't understand any of it. Can you give an example of a typical usage of the PIMPL idiom.
|
A good example where RAII is crucial but sometimes forgotten is when locking a mutex. If you have a section of code that locks a mutex, performs operations, then unlocks it, if the operations throw an exception or otherwise cause the thread to die, the mutex remains locked. This is why there are several scoped lock classes (like QMutexLocker) since as stated here, you are guaranteed that the destructor will run. So if you use a scoped lock it will always unlock on destruction preventing a dead lock.
Pop returns void for the sake of speed: SGI FAQ, and to prevent exceptions that may be thrown by the objects copy constructor.
PIMPL is used heavily by the Qt framework to provide binary compatibility. It allows you to hide all the internals of a data structure from the public API. This means, if you want to add private members to a class, you add it to the d-pointer. This maintains Binary Code Compatibility since the only data member exposed is a pointer.
|
2,388,102 | 2,397,437 | c++ recursive mpl::equal problem? | i need an mpl::equal like procedure that supports recursion on types.
namespace mpl = boost::mpl;
BOOST_MPL_ASSERT(( mpl::equal<
mpl::vector<int, char>,
typename mpl::push_back<mpl::vector<int>, char>::type > )); // OK
the above compiles fine, however if i use it in mpl::transform or mpl::fold, visual studio 2010 rc1 complains.
typedef mpl::vector<
mpl::vector<int, char>,
mpl::vector<char, char>> type_1;
typedef mpl::transform<
mpl::vector<
mpl::vector<int>,
mpl::vector<char>>,
mpl::push_back<mpl::_, char>>::type type_2;
BOOST_MPL_ASSERT(( mpl::equal<type_1, type_2> )); // FAILS
however, these work...
BOOST_MPL_ASSERT(( mpl::equal<
typename mpl::at_c<type_1, 0>::type,
typename mpl::at_c<type_2, 0>::type> )); // OK
BOOST_MPL_ASSERT(( mpl::equal<
typename mpl::at_c<type_1, 1>::type,
typename mpl::at_c<type_2, 1>::type> )); // OK
is it that mpl::equal does not work on dynamically generated recursive types, or is there something wrong with my syntax?
any advice would greatly appreciated.
| mpl::transform doesn't create mpl::vector<>'s in your case but mpl::vector2<>'s. These are different types, even if they are semantically equivalent. So if you write:
typedef mpl::vector2<
mpl::vector2<int, char>, mpl::vector2<char, char>
> type_1;
typedef mpl::transform<
mpl::vector<mpl::vector<int>, mpl::vector<char> >
, mpl::push_back<mpl::_, char>
>::type type_2;
BOOST_MPL_ASSERT(( mpl::equal<type_1, type_2> ));
the assert will not fire.
|
2,388,118 | 2,388,161 | Opening multiple files in C++ | I have this code to open multiple files one at a time that is given at the command line, and then if it cannot open one of the files, it closes all the files and exits.
/* Opens an array of files and returns a pointer to the first
* element (the first file).
*/
ifstream *OpenFiles(char * const fileNames[], size_t count)
{
/* If no command line arguments, error and exit */
if (count == 0) {
cerr << "Invalid number of arguments.";
exit(EXIT_FAILURE);
}
ifstream *fileObj;
fileObj = new ifstream[count];
if (fileObj == NULL) {
cerr << "Failed to create space for files";
exit(EXIT_FAILURE);
}
/* Opens one file at a time and closes all files if there is an
* error opening any file.
*/
for (int loopCount = 0; loopCount < (int)count; loopCount++) {
fileObj[loopCount].open(fileNames[loopCount], ios::out);
if (!fileObj[loopCount].is_open()) {
cerr << "Failed to open " << fileNames[loopCount] << "\n";
for (; loopCount >= 0; loopCount--) {
fileObj[loopCount].close();
cout << "Closed " << fileNames[loopCount] << "\n";
}
delete[] fileObj;
}
}
return fileObj;
}
I am doing this for homework and my teacher has another checker we have to submit to and gives me these types of warnings:
Assign8_1.cpp(44): error 445: (Warning -- Reuse of for loop variable 'loopCount' at 'line 40' could cause chaos)
return fileObj;
Assign8_1.cpp(51): error 850: (Info -- for loop index variable 'loopCount' whose type category is 'integral' is modified in body of the for loop that began at 'line 40')
return fileObj;
Assign8_1.cpp(51): error 449: (Warning -- Pointer variable 'fileObj' previously deallocated [Reference: file Assign8_1.cpp: lines 30, 48])
Assign8_1.cpp(30): error 831: (Info -- Reference cited in prior message)
Assign8_1.cpp(48): error 831: (Info -- Reference cited in prior message)
}
Assign8_1.cpp(63): error 818: (Info -- Pointer parameter 'files' (line 55) could be declared as pointing to const)
}
Starting with the first warning, I was wondering why I shouldn't use my loopCount variable twice the way I do in my code. That was the way I thought it would work, keeping track of which file I am looking at, opening, and closing it appropriately.
Does anyone know what error 449 means? Thanks.
| You need to exit(EXIT_FAILURE) after you delete[] fileObj in the loop, otherwise you'll simply crash on the next iteration. That may be what warning 449 is telling you.
Other than that, the code looks fine. If you want it to compile without those warnings, though, you could turn the inner loop into a standard for-loop which only uses loopCount as a bound. Something like:
for (int i = loopCount; i >= 0; i--) {
fileObj[i].close();
cout << "Closed " << fileNames[i] << "\n";
}
|
2,388,224 | 2,388,231 | Where is the memory for a local C++ vector allocated? | I noticed that the memory for vector is allocated dynamically. So for a local vector, where does the memory is allocated?
f(){
vector<int> vi;
}
| The vector is allocated on the stack (28 bytes on my system). The vector contents are allocated on the heap.
|
2,388,296 | 2,389,300 | Is Qt 4.6 compiled with Cocoa by default on Snow Leopard? | At work, I was told to configure and build Qt 4.6 with the cocoa flag
./configure -cocoa
Instead I just ran configure without any flags on my Mac OS X 10.6 machine.
Does that mean I have to reconfigure or is cocoa linked by default in Snow Leopard?
Alternatively, how can I check if my Qt build is linked against cocoa?
| According to this post -cocoa is only default for 64 bit builds in 4.6 - you have to either supply the -cocoa or -arch x86_64.
If you want to make sure ask configure for its options and look for the defaults.
|
2,388,402 | 2,389,474 | C++ - Load all filename + count the number of files in a current directory + filter file extension | I want to count the number of file in the current directory as well as load all file names in the array. If possible, I want to know how to filter file extension also
| Link the following program with -lboost_filesystem
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem.hpp>
int main( int argc, char ** argv )
{
std::string ext = ".jpg";
std::vector<std::string> files;
for ( boost::filesystem::directory_iterator it( boost::filesystem::initial_path() );
it != boost::filesystem::directory_iterator(); ++it )
{
if ( boost::filesystem::is_regular_file( it->status() ) &&
boost::algorithm::to_lower_copy( it->path().extension() ) == ext )
{
files.push_back( it->path().filename() );
}
}
std::cout << "Number of files: " << files.size() << std::endl;
std::copy( files.begin(), files.end(), std::ostream_iterator<std::string>( std::cout, "\n" ) );
return 0;
}
|
2,388,625 | 2,388,740 | Need help understanding _set_security_error_handler() | So , I've been reading this article:
http://msdn.microsoft.com/en-us/library/aa290051%28VS.71%29.aspx
And I would like to define my custom handler.However, I'm not sure I understand the mechanics well.What happens after a call is made to the user-defined function ( e.g. the argument of _set_security_error_handler() ) ? Does the program still terminate afterward ? If that is the case, is it possible to terminate only the current thread(assuming that it is not the main thread of the application).AFAIK, each thread has its own stack , so if the stack of a thread gets corrupted, the rest of the application shouldn't be affected.
Finally, if it is indeed possible to only terminate the current thread of execution, what potential problems could such an action cause?
I'm trying to do all this inside an unmanaged C++ dll that I would like to use in my C# code.
| The documentation states:
"After handling a buffer overrun, you should terminate the thread or exit the process because the thread's stack is corrupted"
Given this statement, it would seem that you could indeed simply kill the thread. However, you are correct to ask what problems this could cause. The docs for TerminateThread discuss the following problems that can arise from killing a thread:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be released.
If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL
See here: http://msdn.microsoft.com/en-us/library/ms686717(VS.85).aspx
The only "safe" thing to do in this circumstance is to exit the process.
|
2,388,643 | 2,388,929 | Downcasting non-template base class to templated derived class: is it possible? | I'm implementing an event system for a game. It uses an event queue, and a data structure to hold all registered event handlers for a given event type. It works fine so far registering handlers, but when it comes to unregistering them (something that will take place when a game object is destroyed, for instance) I'm having a bit of trouble regarding templates and casting.
I've defined an EventHandler as some sort of functor, partially based on Szymon Gatner's article on http://www.gamedev.net/reference/programming/features/effeventcpp/ . To be precise, I took the HandlerFunctionBase and MemberFunctionHandler class definitions and came up with:
class BaseEventHandler
{
public:
virtual ~BaseEventHandler(){}
void handleEvent(const EventPtr evt)
{
invoke(evt);
}
private:
virtual void invoke(const EventPtr evt)=0;
};
template <class T, class TEvent>
class EventHandler: public BaseEventHandler
{
public:
typedef void (T::*TMemberFunction)(boost::shared_ptr<TEvent>);
typedef boost::shared_ptr<T> TPtr;
typedef boost::shared_ptr<TEvent> TEventPtr;
EventHandler(TPtr instance, TMemberFunction memFn) : mInstance(instance), mCallback(memFn) {}
void invoke(const EventPtr evt)
{
(mInstance.get()->*mCallback)(boost::dynamic_pointer_cast<TEvent>(evt));
}
TPtr getInstance() const{return mInstance;}
TMemberFunction getCallback() const{return mCallback;}
private:
TPtr mInstance;
TMemberFunction mCallback;
};
Then the initial implementation for the unregisterHandler() method on the EventManager class I've thought of would go like this:
// EventHandlerPtr is a boost::shared_ptr<BaseEventHandler>.
// mEventHandlers is an STL map indexed by TEventType, where the values are a std::list<EventHandlerPtr>
void EventManager::unregisterHandler(EventHandlerPtr hdl,TEventType evtType)
{
if (!mEventHandlers.empty() && mEventHandlers.count(evtType))
{
mEventHandlers[evtType].remove(hdl);
//remove entry if there are no more handlers subscribed for the event type
if (mEventHandlers[evtType].size()==0)
mEventHandlers.erase(evtType);
}
}
To make "remove" work here I thought of overloading the == operator for BaseEventHandler, and then using a virtual method to perform the actual comparison...
bool BaseEventHandler::operator== (const BaseEventHandler& other) const
{
if (typeid(*this)!=typeid(other)) return false;
return equal(other);
}
and, on the template class EventHandler, implement the abstract method 'equal' like this:
bool equal(const BaseEventHandler& other) const
{
EventHandler<T,TEvent> derivedOther = static_cast<EventHandler<T,TEvent>>(other);
return derivedOther.getInstance() == this->getInstance() && derivedOther.getCallback()==this->getCallback();
}
Of course, I'm getting a compile error on the static_cast line. I'm not even sure that it is possible at all to do that cast (not necessarily using static_cast). Is there a way to perform it, or at least some workaround that does the trick?
Thanks in advance =)
| In general when closing templates, you need to make sure that > are separated by spaces so the compiler doesn't parse them as a right-shift operator.
Here you're trying to static cast a reference to a non-reference, which even if it worked could invoke object slicing. You need to static cast to a derived reference.
bool equal(const BaseEventHandler& other) const
{
EventHandler<T,TEvent>& derivedOther = static_cast<EventHandler<T,TEvent>&>(other);
return derivedOther.getInstance() == this->getInstance() && derivedOther.getCallback()==this->getCallback();
}
|
2,389,013 | 2,783,364 | QIcon inside combobox | I want to include a "remove" icon on entries in my QComboBox, but I am having trouble catching the mouse press event. I've tried to catch it on the combobox, and I've tried reimplemting the QIcon class to catch the mousepress there. No dice. Does anybody know how to do this?
-D
| I've written code a bit like this, where I wanted to put a tree view inside a combo box and I needed to take an action when the check box on the tree was clicked. What I ended up doing was installing an event filter on the combo box to intercept mouse clicks, figure out where the mouse click was happening, and then take an action. Probably you can do the same kind of thing with your icon. Here is the code:
bool TreeComboBox::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* m = static_cast<QMouseEvent*>(event);
QModelIndex index = view()->indexAt(m->pos());
QRect vrect = view()->visualRect(index);
if(event->type() == QEvent::MouseButtonPress &&
(model()->flags(index) & Qt::ItemIsUserCheckable) &&
vrect.contains(m->pos()))
{
// Your action here
ToggleItem(index);
UpdateSelectionString();
}
if (view()->rect().contains(m->pos()))
skipNextHide = true;
}
return QComboBox::eventFilter(object, event);
}
|
2,389,169 | 3,392,775 | How do I get missing prototype warnings from g++? | I currently have a project that uses g++ to compile it's code. I'm in the process of cleaning up the code, and I'd like to ensure that all functions have prototypes, to ensure things like const char * are correctly handled. Unfortunately, g++ complains when I try to specify -Wmissing-prototypes:
g++ -Wmissing-prototypes -Wall -Werror -c foo.cpp
cc1plus: warning: command line option "-Wmissing-prototypes" is valid for Ada/C/ObjC but not for C++
Can someone tell me:
1) Why does gcc this isn't valid? Is this a bug in gcc?
2) Is there a way to turn on this warning?
EDIT:
Here's a cut and paste example:
cat > foo.cpp <<EOF
void myfunc(int arg1, int arg2)
{
/* do stuff with arg1, arg2 */
}
EOF
g++ -Wmissing-prototypes -c foo.cpp # complains about not valid
g++ -c foo.cpp # no warnings
# Compile in C mode, warning appears as expected:
g++ -x c -Wmissing-prototypes -c foo.cpp
| Did you try -Wmissing-declarations? That seems to work for g++ and detect the error case you describe. I'm not sure which version they added it in, but it works for me in 4.3.3.
|
2,389,270 | 2,389,296 | Visual Studio - can be a breakpoint called from code? | I have a unit test project based on UnitTest++. I usually put a breakpoint to the last line of the code so that the I can inspect the console when one of the tests fails:
n = UnitTest::RunAllTests();
if ( n != 0 )
{
// place breakpoint here
return n;
}
return n;
But I have to reinsert it each time I check-out the code anew from SVN. Is it possible to
somewhat place the breakpoint by the compiler?:
n = UnitTest::RunAllTests();
if ( n != 0 )
{
// place breakpoint here
#ifdef __MSVC__
@!!!$$$??___BREAKPOINT;
#endif
return n;
}
return n;
| Use the __debugbreak() intrinsic(requires the inclusion of <intrin.h>).
Using __debugbreak() is preferable to directly writing __asm { int 3 } since inline assembly is not permitted when compiling code for the x64 architecture.
And for the record, on Linux and Mac, with GCC, I'm using __builtin_trap().
|
2,389,391 | 2,389,430 | Running function from an unmanaged dll inside a C# thread | Here's my problem:
I have an unmanaged dll that I made.I'm calling one of this dll's functions in my C# code, using PInvoke.
Under certain conditions, in the dll function, I want to be able to terminate the thread that is running the function.How would I achieve that?
Sorry if it is a stupid question, but I'm a total noob when it comes to threading:)
| Man, that sounds dangerous. Why terminate the thread? You might be in a thread you don't own depending on how you're marshalling the call. Either ways, it seems like your best option is to return something to indicate you want to terminate the thread and have the managed code handle it gracefully. Don't try to kill the thread in native code.
|
2,389,472 | 4,054,371 | string conversion between UTF-8 representation and unicode representation | How to design an algorithm to convert a UTF-8 string to a unicode string?
| The commenters are right. Read http://en.wikipedia.org/wiki/Unicode and rephrase question.
UTF-8 is a ''represenation'' of unicode. You probably want to recode to some other interpretation, maybe Java Strings or Microsoft Visual C++ multibyte chracter strings...
|
2,389,520 | 2,389,594 | Class structure for an inventory control system | As an exercise in good OO methods and design, I want to know what is a good way to model inventory control in a company. The problem description is
a. A company can have different types of items, like documents (both electronic and physical), computers etc which may further have their own sub types.
b. The items can be kept in a store, may be circulated to an employee, may be mailed out etc. An electronic document can be emailed to many people at a time.
c. Items may have certain restrictions like a classified document be circulated to only people/places with access (eg, people with classified clearance or a room cleared to store those documents etc)
what is a good class structure(s) that can be used to model this kind of tracking? (pseudo C# class structure or c++ would be helpful) and what kind of design patterns would be good for such a task
| Answering your question would need deep investigation of the problem domain. I don't think there is a universally valid approach.
There are some patterns that are likely to appear, though. One of them (and one of the most difficult to implement, by the way), is the type/instance pattern. Based on my experience, I am assuming that the types of the items that your inventory app must keep track of cannot be fixed, and that users of your system must be able to create and modify types at any time. This means that your system needs to handle two levels of classification rather than the usual one; in other words, your system will have classes (in code), instances of those classes (in run-time) and instances of those instances (in run-time too).
For example, if you create the DocumentType class in code, your users would instantiate it a number of times, creating objects such as Report, Memo or Manual. Then, each individual report that your system manages would be an instance of Report. And each individual memo would be an instance of Memo. And so on.
This is easy to implement if subtypes (Report, Memo, Manual in my example) don't carry their own attributes or their own relationships to other pieces of information. However, if they need specific data structures (attributes and/or associations), then the problem becomes much harder, because you'll need to mimic a complete object-oriented type/instance engine within your system.
It's lots of fun, though!
|
2,389,527 | 2,784,084 | Boost.Program_options fixed number of tokens | Boost.Program_options provides a facility to pass multiple tokens via command line arguments as follows:
std::vector<int> nums;
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce help message.")
("nums", po::value< std::vector<int> >(&nums)->multitoken(), "Numbers.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
However, what is the preferred way of accepting only a fixed number of arguments? The only solution I could come is to manually assign values:
int nums[2];
po::options_description desc("Allowed options");
desc.add_options()
("help", "Produce help message.")
("nums", "Numbers.")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("nums")) {
// Assign nums
}
This feels a bit clumsy. Is there a better solution?
| The boost library only provides the predefined mechanisms. A quick search didn't find something with a fixed number of values. But you can create this yourself. The po::value< std::vector<int> >(&nums)->multitoken() is just a specialized value_semantic class. As you can see, this class offers the methods min_tokens and max_tokens, which seems to do exactly what you want. If you look at the definition of class typed_value ( this is the object that gets created, when you call po::value< std::vector<int> >(&nums)->multitoken()) you can get the grasp of how the methods should be overridden.
|
2,389,583 | 2,389,682 | Need to traverse matrix-like graph in expanding concentric squares | Ok, I've a data structure that consists of a matrix of linked nodes, lets say 10x10. I would like to be able to choose any of these nodes arbitrarily, and - from there - process a number of the surrounding nodes following the pattern of expanding concentric squares (I used less nodes below for illustration purposes). As far as specifics go, the implementation will be in Actionscript - but feel free to answer in another language :) - and it's for a minesweeper game (specifically the feature where, if clicking on a patch of mine-less squares, they -all- get cleared regardless of irregular shape, up to the surrounding mines). It will also be event based - dispatching one for each node traversed, so the way I imagine it is that when the iterator or whatever comes across a field containing a mine, traversal would stop from going further in that direction while the rest would continue. The nodes are doubly linked to their top, right, bottom, and left neighbors, and I wouldn't be opposed to adding more links if necessary. There's probably some other way to do it, but I can think of a number of uses for this kind of solution and would like to include it in a framework I'm creating, so I'd like to walk away with something I can reuse.
first:
0 0 0 0 0
0 0 0 0 0
0 0 X 0 0
0 0 0 0 0
0 0 0 0 0
second:
0 0 0 0 0
0 X X X 0
0 X 0 X 0
0 X X X 0
0 0 0 0 0
third:
X X X X X
X 0 0 0 X
X 0 0 0 X
X 0 0 0 X
X X X X X
| function scan( x, y ){
queue toDo;
set queued;
toDo.push( x, y );
queued.add( x, y );
while ( !toDo.empty() ) {
(x, y) = toDo.removeHead();
if ( process( x, y ) != stop ) {
for( xp = -1; xp <= 1; ++xp ) {
for( yp = -1; yp <= 1; ++yp ) {
if ( !queued.contains( x+xp, y+yp ) ) {
toDo.push( x+xp, y+yp );
queued.add( x+xp, y+yp );
}
}
}
}
}
}
|
2,389,663 | 2,390,174 | First while loop's first iteration always fails to take input. 2+ loops work fine | The bug starts at cin.getline ( string, 25, '\n' ); or the line below it (strtod). If I use cin, it works, except I cannot quit out. If I type anything that's not a double, an infinite loop runs. Need help. Basically, the first iteration runs, does not ask for input, so the user gets the math questions wrong. The second iteration works fine. And the next is fine, too. If I back out, using q, I get dumped back to the mode-chooser. After choosing a mode, the bug reappears for the first iteration. Next iterations it's gone.
int main()
{
char choice, name[25], string[25], op;
int operator_number, average, difference, first_operand, second_operand, input, answer, total_questions = 0, total_correct = 0;
double dfirst_operand, dsecond_operand, dinput, danswer, percentage;
bool rounding = false;
srand ( time(NULL) );
cout << "What's your name?\n";
cin.getline ( name, 25, '\n' );
cout << '\n' << "Hi, " << name << ".";
do {
do {
cout << "\nWhich math operations do you want to practice?\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n 5. Mixed\n 6. Difference of squares multiplication.\nChoose a number (q to quit).\n";
cin >> choice;
} while( choice < '1' || choice > '6' && choice!= 'q');
cout << "\n";
switch(choice) {
case '1':
while( string[0]!= 'q') {
dfirst_operand = rand() % 15 + 1;
dsecond_operand = rand() % 15 + 1;
danswer = dfirst_operand + dsecond_operand;
cout << dfirst_operand << " + " << dsecond_operand << " equals?\nEnter q to quit.\n";
cin.getline ( string, 25, '\n' );
dinput = strtod( string,NULL);
//cin >> dinput;
if(string[0]!='q') {
++total_questions;
if(dinput==danswer) {
++total_correct;
cout << "Correct. " << total_correct << " correct out of " << total_questions << ".";
} else {
cout << "Wrong. " << dfirst_operand << " + " << dsecond_operand << " equals " << danswer << ".\n" << total_correct << " correct out of " << total_questions << ".";
};
percentage = floor(10000 * (float) total_correct / total_questions)/100;
cout << ' ' << percentage << "%.\n\n";
}
}
break;
}
} while(choice!='q');
return 0;
}
| The problem is this line:
cin >> choice;
This line parses the input buffer for character input that can be converted to an integer. So if you enter:
2<newline>
The string "2" is converted, and <newline> remains in the input buffer; so the subsequent cin.getline() is satisfied immediately.
This is also why JonH's suggestion does not work, you need to purge the input buffer after the cin << choice input. An alternative is to use cin.getline() for all input (or better; use ::getline() which operates on std::string rather than C-strings), and then parse that input using a std::istringstream object when you need formatted input scanning.
However if you must use cin.ignore() to solve this problem, you should do it thus:
cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ) ;
where std::numeric_limits is defined in the header. Your solution trusts the user not to enter more than 25 characters. That is not a very safe assumption.
|
2,389,886 | 2,389,988 | How do I strong name a C++ assembly in VS2008? | I have no experience developing C++ on Windows, but I am a C# developer.
I have a wrapper around some native DLLs that is written in C++. (A LGPL project)). I was to use this from a strong named assembly.
How do I set up the strong naming of the C++ assembly? There is no 'Signing' properties tab available as there is in C# projects.
I imagine that I need to edit the vcproj file and put a reference to the key file, something like
/KEYFILE:"sgKey.snk"
that I found at this site: http://www.windows-tech.info/17/6a8f0ab94246fb61.php
I'm sure it will be easy once I find the right reference. Can someone point me in the right direction?
An easy question for C++ devs to get some rep points out of.
Thanks.
| I found it. For some reason the first time I clicked on the project the property pages came up empty. On retry I found it in the project property page.
Configuration Propertyes|Linker|Advanced|Key File.
And just enter the path to the snk key file.
Thanks for looking.
|
2,390,131 | 2,390,154 | printf question with a const char* variable | I am stuck in a printf problem. I would appreciate if I can get some help here:
In the below code, I can see the font family get displaced correctly in first printf(),
but if I set it to variable, i only get an empty string. How can I put it in a variable and have the right values? I just don't want to type 'font.family().family().string().utf8().data()' everywhere?
I did this in the same method:
void myMethod() {
const char* fontFamily = font.family().family().string().utf8().data();
// get displayed correctly
printf ("drawText1 %s \n", font.family().family().string().utf8().data());
// get an empty string
printf ("drawText2 %s \n", fontFamily);
}
And the signature of 'data()' is
class CString {
public:
CString() { }
CString(const char*);
CString(const char*, unsigned length);
CString(CStringBuffer* buffer) : m_buffer(buffer) { }
static CString newUninitialized(size_t length, char*& characterBuffer);
const char* data() const;
//...
}
The signature of utf8() is
class String {
CString utf8() const;
}
Thank you.
| Something in the chain of font.family().family().string().utf8().data() is returning a temporary object. In your first printf, the temporary object doesn't go out of scope until the printf returns. In the second printf, the temporary has been destroyed after the pointer assignment was made, and the pointer is now invalid. You're seeing a classic example of "undefined behavior".
There are two ways to fix this. Either make a copy of the data before the temporary gets destroyed, or make a reference to the temporary. The copy is probably easiest and clearest, as long as the class has a copy operator. Assuming that utf8() generates a temporary CString, this would be
CString fontFamily = font.family().family().string().utf8();
printf ("drawText2 %s \n", fontFamily.data());
|
2,390,782 | 2,390,838 | OpenGL texture mapping on sides cube using GL_QUADS | I am trying to map a different texture on each side of a cube using a GL_QUADS. My first problem is that I cannot even get a texture to display on the side of a GL_QUADS. I can however get a texture to display using GL_TRIANGLES but I do no understand how to draw things very well using triangles and I want to use QUADS. I also can only use GLUT for this. I need an example that works because I do not know enough about OpenGL for someone to simply explain this to me. Someone please help. Thanks!
| Oops didn't realize I forgot to use glTexCoord2f. It works now.
|
2,390,861 | 2,390,880 | Checking ignore() for values | When you use ignore() in C++, is there a way to check those values that were ignored? I basically am reading some # of chars and want to know if I ignored normal characters in the text, or if I got the newline character first. Thanks.
| I don't believe so - you'd have to "roll your own".
In other words, I think you'd have to write some code that read from the stream using get(), and then add some logic for keeping what you need and ignoring the rest (whilst checking to see what you're ignoring).
|
2,390,897 | 2,390,956 | C++ inheritance, base functions still being called when overriden | I have the following two classes, one inherits from the other
Class A{
void print(){cout << "A" << endl;}
}
Class B : A{
void print(){cout << "B" << endl;}
}
Class C : A{
void print(){cout << "C" << endl;}
}
Then in another class I have the following:
vector<A> things;
if (..)
things.push_back(C());
else if (..)
things.push_back(B());
things[0].print();
this always prints A
I'd like it to print B or C depending on which thing I've added to the vector
how do I do this?
I've tried abstraction but I'm not entirely sure how to use it in C++ and it hasn't been working for me
| As mentioned, you need virtual functions to enable polymorphic behaviour and can't store classes directly by value in the vector.
When you use a std::vector<A>, you are storing by value and thus objects that you add, e.g. via push_back() are copied to an instance of an A, which means you lose the derived part of the objects. This problem is known as object slicing.
As already suggested you can avoid that by storing pointers (or smart pointers) to the base class, so only pointers are copied into the vector:
std::vector<A*> things;
things.push_back(new B());
// ... use things:
things[0]->print();
// clean up later if you don't use smart pointers:
for(std::vector<A*>::iterator it = things.begin(); it != things.end(); ++it)
delete *it;
|
2,390,911 | 2,391,231 | SSPI Negotiate not found | I'm using Windows XP Pro SP3.
I want to use SSPI functions in my code.
I compiled my code, no error.
I set the security package to be used to Negotiate, which is recommended.
When I start my program, Negotiate cannot be used because it can't be found.
So, I tried "Kerberos" instead, and same error: the security package cannot be found.
I had a look at the registry, and according to that key: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/Lsa/Security Packages, the security packages available are: kerberos, msv1_0, schannel, wdigest. Negotiate and NTLM are missing.
I don't understand why my program can't find any security package.
The returned error code is 0x80090305 and I couldn't find any hint about a way to fix it.
So, if you master the SSPI, please I need your help!
Do I have something to modify in the registry?
Or maybe I need to register some DLLs?
Thanks for any hint
Bye!
| SSPI is a cow to debug without code :)
Try this code, see if it works, if it does, re-try it and replace NTLM with Negotiate. Actually, rather than using the word, "Negotiate" #include "security.h" and use NEGOSSP_NAME.
Also, try this, and see if Negotiate is in the list:
int main(int argc, _TCHAR* argv[])
{
ULONG cPackages = 0;
PSecPkgInfo pInfo = NULL;
SECURITY_STATUS stat = EnumerateSecurityPackages(&cPackages, &pInfo);
if (stat == SEC_E_OK) {
for (ULONG i = 0; i < cPackages; i++) {
wprintf(L"%s\t%s\n",pInfo[i].Name, pInfo[i].Comment);
}
FreeContextBuffer(pInfo);
}
return 0;
}
make sure you define SECURITY_WIN32 in your header, and link with secur32.
|
2,390,912 | 2,390,938 | Checking for an empty file in C++ | Is there an easy way to check if a file is empty. Like if you are passing a file to a function and you realize it's empty, then you close it right away? Thanks.
Edit, I tried using the fseek method, but I get an error saying 'cannot convert ifstream to FILE *'.
My function's parameter is
myFunction(ifstream &inFile)
| Perhaps something akin to:
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
Short and sweet.
With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.
Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it's eof(), since an empty file has nothing to peek at.
Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:
std::ifstream file("filename");
if (!file)
{
// file is not open
}
if (is_empty(file))
{
// file is empty
}
// file is open and not empty
|
2,391,062 | 2,391,073 | Follow-up. Is return reference to x++ defined? | I recently asked the question Is the behavior of return x++; defined?
The result was about what I expected, but got me thinking about a similar situation.
If I were to write
class Foo
{
...
int x;
int& bar() { return x++; }
};
Where bar now returns an int reference, is this behavior defined? If the answer to the previous question is literally true and not just a convenient abstraction of what's going on, it would seem you'd return a reference to a stack variable that would be destroyed as soon as the return was executed.
If it is just an abstraction, I'd be interested to know what behavior is actually guaranteed by a post-increment.
| No, you cannot do that, as that would be returning a reference to a temporary.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.