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
|
|---|---|---|---|---|
294,007
| 294,088
|
How to prevent a new window from opening in hosted Internet Explorer
|
I'm hosting an Internet Explorer instance (the Web Control) in an CAxWindow ATL class. How do I prevent that a website could open a new window from the hosted IE? I'm already setting an implementation of IDocHostUIHandlerDispatch to disable the context menu.
|
There is an event on the WebBrowser ActiveX control for displaying a new window (NewWindow, NewWindow2, NewWindow3) that you need to listen to and cancel.
|
294,009
| 840,996
|
Elegant Object comparison
|
When comparing two objects (of the same type), it makes sense to have a compare function which takes another instance of the same class. If I implement this as a virtual function in the base class, then the signature of the function has to reference the base class in derived classes also. What is the elegant way to tackle this? Should the Compare not be virtual?
class A
{
A();
~A();
virtual int Compare(A Other);
}
class B: A
{
B();
~B();
int Compare(A Other);
}
class C: A
{
C();
~C();
int Compare(A Other);
}
|
It depends on the intended semantics of A, B, and C and the semantics of compare(). Comparison is an abstract concept that doesn't necessarily have a single correct meaning (or any meaning at all, for that matter). There is no single right answer to this question.
Here's two scenarios where compare means two completely different things with the same class hierarchy:
class Object
{
virtual int compare(const Object& ) = 0;
float volume;
};
class Animal : Object
{
virtual int compare(const Object& );
float age;
};
class Zebra : Animal
{
int compare(const Object& );
};
We can consider (at least) two ways of comparing two Zebras: which is older, and which has more volume? Both comparisons are valid and easily computable; the difference is that we can use volume to compare a Zebra with any other Object, but we can only use age to compare Zebras with other Animals. If we want compare() to implement the age comparison semantics, it doesn't make any sense to define compare() in the Object class, since the semantics aren't defined at this level of the hierarchy. It's worth noting that neither of these scenarios require any casting, whatsoever, as the semantics are defined at the level of the base class (whether it be Object when comparing volume, or Animal when comparing age).
This raises the more important issue -- that some classes aren't suited to a single catch-all compare() function. Often it makes more sense to implement multiple functions that explicitly state what is being compared, like compare_age() and compare_volume(). The definition of these functions can occur at the point in the inheritance hierarchy where the semantics become relevant, and it should be trivial to adapt them to child classes (if the need adapting at all). Simple comparison using compare() or operator==() often only make sense with simple classes where the correct semantic implementation is obvious and unambiguous.
Long story short... "it depends".
|
294,018
| 294,023
|
What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?
|
What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?
An example:
class A
{
public:
char s[1024];
char *p;
A::A()
{
p = s;
}
void changeS() const
{
p[0] = 'a';
}
};
Even know changeS is a const member function, it is changing the value of the object. So a const member function only means that it will treat all variables as const, and it does not mean that it will actually keep all members const. (why? the const keyword on the member function treats char *p; as char * const p; And not as const char *p;
Which therefore means that p can't point to something else. And not that you can't change p's data.
|
I've liked this since the time i've discovered it in some code:
assert(condition || !"Something has gone wrong!");
or if you don't have a condition at hand, you can just do
assert(!"Something has gone wrong!");
The following is attributed to @Josh (see comments). It uses the comma operator instead:
assert(("Something has gone wrong!", condition));
|
294,261
| 294,283
|
tr1::mem_fn and members with default arguments
|
I have class with a member function that takes a default argument.
struct Class
{
void member(int n = 0)
{}
};
By means of std::tr1::mem_fn I can invoke it:
Class object;
std::tr1::mem_fn(&Class::member)(object,10);
That said, if I want to invoke the callable member on the object with the default argument, what's the correct syntax?
std::tr1::mem_fn(&Class::member)(object); // This does not work
g++ complains with the following error:
test.cc:17: error: no match for call to ‘(std::tr1::_Mem_fn<void (Class::*)(int)>) (Class&)’
/usr/include/c++/4.3/tr1_impl/functional:551: note: candidates are: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class&, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int]
/usr/include/c++/4.3/tr1_impl/functional:556: note: _Res std::tr1::_Mem_fn<_Res (_Class::*)(_ArgTypes ...)>::operator()(_Class*, _ArgTypes ...) const [with _Res = void, _Class = Class, _ArgTypes = int]
Still, the I have the same problem when Class::member is overloaded by members that takes different arguments...
|
Default functions are bound at call time, but can't be bound into any sort of wrapper implicitly, because of the way they are implemented. When you pass &Class::member, mem_fn only sees a void (Class::*)(int), and can't see the default argument. Using tr1::bind, you can bind the default argument explictly: std::tr1::bind(&Class::member, 0) or you can use it as you would mem_fn, but you can't do both in one object. You would have to write your own wrapper class for that.
As for overloads, you will have to explicitly specify the template arguments for mem_fn so the right function pointer is picked as in mem_fn<void(int)>(&Class::member).
|
294,270
| 294,278
|
How do you call a constructor for global objects, for arrays of objects, and for objects inside classes/structs?
|
How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?
The class with the constructor (used in all three examples):
class Foo {
public:
Foo(int a) { b = a; }
private:
int b;
};
And here are my attempts at calling this constructor:
Global objects
Foo global_foo(3); // works, but I can't control when the constructor is called.
int main() {
// ...
}
Arrays of objects
int main() {
// Array on stack
Foo array_of_foos[30](3); // doesn't work
// Array on heap
Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work
}
There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements.
Objects contained in classes/structs
class Bar {
Foo foo(3); // doesn't work
};
int main() {
Bar bar;
}
|
Global objects
Yours is the only way. On the other hand, try to avoid this. It’s better to use functions (or even other objects) as factories instead. That way, you can control the time of creation.
Arrays of objects
There’s no way to do this directly. Non-POD objects will always be default-constructed. std::fill is often a great help. You might also want to look into allocators and std::uninitialized_fill.
Objects contained in classes/structs
Use initialization lists in your constructor:
class Bar {
Foo foo;
Bar() : foo(3) { }
};
Static members must actually be defined outside the class:
class Bar {
static Foo foo;
};
Foo Bar::foo(3);
|
294,554
| 294,636
|
Where can I find C/C++ users journal archive in suitable format (not .html)?
|
I am searching for this magazine for quite a long time and I can`t find it.
|
they merged with frobbs a couple years ago: http://www.ddj.com/cpp/cuj.jhtml. you might find something there.
|
294,680
| 294,756
|
How to improve performance of an Abstract Factory when all the time appears to be spent in memory allocation
|
The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory). It's too slow. Profiling says all the time is spent in operator new.
Notes: The application already uses a custom memory allocator that does pooling. The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.
The only idea I have right now is to introduce Object Pooling. I'd maintain large collections of pre-allocated objects for each type and re-use them. But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help. I was hoping someone smarter than me has an idea.
|
The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation? Are you possibly doing some string manipulation?
If all the time is spent allocating the objects the factory is creating, you may need to go to a pool.
|
294,852
| 295,510
|
References Needed for Implementing an Interpreter in C/C++
|
I find myself attached to a project to integerate an interpreter into an existing application. The language to be interpreted is a derivative of Lisp, with application-specific builtins. Individual 'programs' will be run batch-style in the application.
I'm surprised that over the years I've written a couple of compilers, and several data-language translators/parsers, but I've never actually written an interpreter before. The prototype is pretty far along, implemented as a syntax tree walker, in C++. I can probably influence the architecture beyond the prototype, but not the implementation language (C++). So, constraints:
implementation will be in C++
parsing will probably be handled with a yacc/bison grammar (it is now)
suggestions of full VM/Interpreter ecologies like NekoVM and LLVM are probably not practical for this project. Self-contained is better, even if this sounds like NIH.
What I'm really looking for is reading material on the fundamentals of implementing interpreters. I did some browsing of SO, and another site known as Lambda the Ultimate, though they are more oriented toward programming language theory.
Some of the tidbits I've gathered so far:
Lisp in Small Pieces, by Christian Queinnec. The person recommending it said it "goes from the trivial interpreter to more advanced techniques and finishes presenting bytecode and 'Scheme to C' compilers."
NekoVM. As I've mentioned above, I doubt that we'd be allowed to incorporate an entire VM framework to support this project.
Structure and Interpretation of Computer Programs. Originally I suggested that this might be overkill, but having worked through a healthy chunk, I agree with @JBF. Very informative, and mind-expanding.
On Lisp by Paul Graham. I've read this, and while it is an informative introduction to Lisp principles, is not enough to jump-start constructing an interpreter.
Parrot Implementation. This seems like a fun read. Not sure it will provide me with the fundamentals.
Scheme from Scratch. Peter Michaux is attacking various implementations of Scheme, from a quick-and-dirty Scheme interpreter written in C (for use as a bootstrap in later projects) to compiled Scheme code. Very interesting so far.
Language Implementation Patterns: Create Your Own Domain-Specific and General Programming Languages, recommended in the comment thread for Books On Creating Interpreted Languages. The book contains two chapters devoted to the practice of building interpreters, so I'm adding it to my reading queue.
New (and yet Old, i.e. 1979): Writing Interactive Compilers and Interpreters by P. J. Brown. This is long out of print, but is interesting in providing an outline of the various tasks associated with the implementation of a Basic interpreter. I've seen mixed reviews for this one but as it is cheap (I have it on order used for around $3.50) I'll give it a spin.
So how about it? Is there a good book that takes the neophyte by the hand and shows how to build an interpreter in C/C++ for a Lisp-like language? Do you have a preference for syntax-tree walkers or bytecode interpreters?
To answer @JBF:
the current prototype is an interpreter, and it makes sense to me as we're accepting a path to an arbitrary code file and executing it in our application environment. The builtins are used to affect our in-memory data representation.
it should not be hideously slow. The current tree walker seems acceptable.
The language is based on Lisp, but is not Lisp, so no standards compliance required.
As mentioned above, it's unlikely that we'll be allowed to add a full external VM/interpreter project to solve this problem.
To the other posters, I'll be checking out your citations as well. Thanks, all!
|
Short answer:
The fundamental reading list for a lisp interpreter is SICP. I would not at all call it overkill, if you feel you are overqualified for the first parts of the book jump to chapter 4 and start interpreting away (although I feel this would be a loss since chapters 1-3 really are that good!).
Add LISP in Small Pieces (LISP from now on), chapters 1-3. Especially chapter 3 if you need to implement any non-trivial control forms.
See this post by Jens Axel Søgaard on a minimal self-hosting Scheme: http://www.scheme.dk/blog/2006/12/self-evaluating-evaluator.html .
A slightly longer answer:
It is hard to give advice without knowing what you require from your interpreter.
does it really really need to be an interpreter, or do you actually need to be able to execute lisp code?
does it need to be fast?
does it need standards compliance? Common Lisp? R5RS? R6RS? Any SFRIs you need?
If you need anything more fancy than a simple syntax tree walker I would strongly recommend embedding a fast scheme subsystem. Gambit scheme comes to mind: http://dynamo.iro.umontreal.ca/~gambit/wiki/index.php/Main_Page .
If that is not an option chapter 5 in SICP and chapters 5-- in LISP target compilation for faster execution.
For faster interpretation I would take a look at the most recent JavaScript interpreters/compilers. There seem to be a lot of thought going into fast JavaScript execution, and you can probably learn from them. V8 cites two important papers: http://code.google.com/apis/v8/design.html and squirrelfish cites a couple: http://webkit.org/blog/189/announcing-squirrelfish/ .
There is also the canonical scheme papers: http://library.readscheme.org/page1.html for the RABBIT compiler.
If I engage in a bit of premature speculation, memory management might be the tough nut to crack. Nils M Holm has published a book "Scheme 9 from empty space" http://www.t3x.org/s9fes/ which includes a simple stop-the-world mark and sweep garbage collector. Source included.
John Rose (of newer JVM fame) has written a paper on integrating Scheme to C: http://library.readscheme.org/servlets/cite.ss?pattern=AcmDL-Ros-92 .
|
294,927
| 294,932
|
Does delete work with pointers to base class?
|
Do you have to pass delete the same pointer that was returned by new, or can you pass it a pointer to one of the classes base types? For example:
class Base
{
public:
virtual ~Base();
...
};
class IFoo
{
public:
virtual ~IFoo() {}
virtual void DoSomething() = 0;
};
class Bar : public Base, public IFoo
{
public:
virtual ~Bar();
void DoSomething();
...
};
Bar * pBar = new Bar;
IFoo * pFoo = pBar;
delete pFoo;
Of course this is greatly simplified. What I really want to do is create a container full of boost::shared_ptr and pass it to some code that will remove it from the container when it is finished. This code will know nothing of the implementation of Bar or Base, and will rely on the implied delete operator in the shared_ptr destructor to do the right thing.
Can this possibly work? My intuition says no, since the pointers will not have the same address. On the other hand, a dynamic_cast<Bar*> should work, so somewhere the compiler is storing enough information to figure it out.
Thanks for the help, everybody who answered and commented. I already knew the importance of virtual destructors, as shown in my example; after seeing the answer I gave it a little thought, and realized the whole reason for a virtual destructor is this exact scenario. Thus it had to work. I was thrown by the absence of a visible means of converting the pointer back to the original. A little more thinking led me to believe there was an invisible means, and I theorized that the destructor was returning the true pointer for delete to release. Investigating the compiled code from Microsoft VC++ confirmed my suspicion when I saw this line in ~Base:
mov eax, DWORD PTR _this$[ebp]
Tracing the assembler revealed that this was the pointer being passed to the delete function. Mystery solved.
I've fixed the example to add the virtual destructor to IFoo, it was a simple oversight. Thanks again to everyone who pointed it out.
|
Yes, it will work, if and only if the base class destructor is virtual, which you have done for the Base base class but not for the IFoo base class. If the base class destructor is virtual, then when you call operator delete on the base class pointer, it uses dynamic dispatch to figure out how to delete the object by looking up the derived class destructor in the virtual function table.
In your case of multiple inheritance, it will only work if the base class you're deleting it through has a virtual destructor; it's ok for the other base classes to not have a virtual destructor, but only if you don't try to delete any derived objects via those other base class pointers.
|
295,013
| 295,023
|
Using sprintf without a manually allocated buffer
|
In the application that I am working on, the logging facility makes use of sprintf to format the text that gets written to file. So, something like:
char buffer[512];
sprintf(buffer, ... );
This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.
Is there a way to get sprintf behaviour without having to manually allocate memory like this?
EDIT: while sprintf is a C operation, I'm looking for C++ type solutions (if there are any!) for me to get this sort of behaviour...
|
No you can't use sprintf() to allocate enough memory. Alternatives include:
use snprintf() to truncate the message - does not fully resolve your problem, but prevent the buffer overflow issue
double (or triple or ...) the buffer - unless you're in a constrained environment
use C++ std::string and ostringstream - but you'll lose the printf format, you'll have to use the << operator
use Boost Format that comes with a printf-like % operator
|
295,027
| 296,143
|
Array of zero length
|
I am working on refactoring some old code and have found few structs containing zero length arrays (below). Warnings depressed by pragma, of course, but I've failed to create by "new" structures containing such structures (error 2233). Array 'byData' used as pointer, but why not to use pointer instead? or array of length 1? And of course, no comments were added to make me enjoy the process...
Any causes to use such thing? Any advice in refactoring those?
struct someData
{
int nData;
BYTE byData[0];
}
NB It's C++, Windows XP, VS 2003
|
Yes this is a C-Hack.
To create an array of any length:
struct someData* mallocSomeData(int size)
{
struct someData* result = (struct someData*)malloc(sizeof(struct someData) + size * sizeof(BYTE));
if (result)
{ result->nData = size;
}
return result;
}
Now you have an object of someData with an array of a specified length.
|
295,067
| 295,080
|
Passing an array using COM?
|
I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two. My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.).
Is there a relatively easy way to have the COM object pass an array to the caller? For example, I want to pass a raw image (TIFF) instead of messing with temporary files.
|
Try passing a safearray variant to the COM Object. Something like this to put a BYTE array inside a safearray variant....
bool ArrayToVariant(CArray<BYTE, BYTE>& array, VARIANT& vtResult)
{
SAFEARRAY FAR* psarray;
SAFEARRAYBOUND sabounds[1];
sabounds[0].lLbound=0;
sabounds[0].cElements = (ULONG)array.GetSize();
long nLbound;
psarray = SafeArrayCreate(VT_UI1, 1, sabounds);
if(psarray == NULL)
return false;
for(nLbound = 0; nLbound < (long)sabounds[0].cElements ; nLbound++){
if(FAILED(SafeArrayPutElement(psarray, &nLbound, &array[nLbound]))){
SafeArrayDestroy(psarray);
return false;
}
}
VariantFree(vtResult);
vtResult.vt = VT_ARRAY|VT_UI1;
vtResult.parray = psarray;
return true;
}
|
295,120
| 21,192,071
|
C++ mark as deprecated
|
I have a method in an interface that I want to deprecate with portable C++.
When I Googled for this all I got was a Microsoft specific solution; #pragma deprecated and __declspec(deprecated).
A second prize solution would be to ifdef a MSVC and a GCC solution.
|
In C++14, you can mark a function as deprecated using the [[deprecated]] attribute (see section 7.6.5 [dcl.attr.deprecated]).
The attribute-token deprecated can be used to mark names and entities whose use is still allowed, but is discouraged for some reason.
For example, the following function foo is deprecated:
[[deprecated]]
void foo(int);
It is possible to provide a message that describes why the name or entity was deprecated:
[[deprecated("Replaced by bar, which has an improved interface")]]
void foo(int);
The message must be a string literal.
For further details, see “Marking as deprecated in C++14”.
|
295,169
| 295,264
|
What are the practical differences between C compilers on Windows?
|
A program written in Visual C/C++ 2005/2008 might not compile with another compiler such as GNU C/C++ or vice-versa. For example when trying to reuse code, which uses windows.h, written for a particular compiler with another, what are the differences to be aware of?
Is there any information about how to produce code which is compatible with either one compiler or another e.g. with either GC/C++ or MSVC/C++? What problems will attempting to do this cause?
What about other compilers, such as LCC and Digital Mars?
|
The first thing to do when trying to compile code written for MSVC to other compilers is to compile it with Microsoft-extensions switched off. (Use the /Za flag, I think). That will smoke out lots of things which GCC and other compilers will complain about.
The next step is to make sure that Windows-specific APIs (MFC, Win32, etc.) are isolated in Windows-specific files, effectively partioning your code into "generic" and "windows-specific" modules.
|
295,279
| 295,288
|
What is the fastest way to get the 4 least significant bits in a byte (C++)?
|
I'm talking about this:
If we have the letter 'A' which is 77 in decimal and 4D in Hex.
I am looking for the fastest way to get D.
I thought about two ways:
Given x is a byte.
x << 4; x >> 4
x %= 16
Any other ways? Which one is faster?
|
I always use x &= 0x0f
|
295,506
| 321,649
|
T4 Templates - suitable for generating C++ code?
|
Are there any issues which might make MS's T4 Template code-generation system unsuitable for generating C++ code?
|
It can generate any text you want, including C++ code.
|
295,533
| 640,475
|
Wrapping boost::signal to C# delegates
|
say I have an asynchronous library, written in native C++, with an interface similar to this:
class connection {
public:
boost::signal< void() > sig_connection_made;
boost::signal< void(const std::string&) > sig_error;
void connect(const std::string& host, const std::string& port);
};
that I want to wrap in C#. Does anyone know of a way, using SWIG or something similar, that will allow me to bind the signals to C# delegates?
|
you can pass a delegate into c++ from C# using SWIG assign it to a function pointer and then call the function pointer and it will trigger the delegate.
|
296,657
| 296,689
|
Defining macros in Visual Studio - /D or #define?
|
Recently, when porting some STL code to VS2008 I wanted to disable warnings generated by std::copy by defining the new _SCL_SECURE_NO_WARNINGS flag. You can do this in two ways:
Using the /D compiler switch, which can be specified in the project properties. You need to ensure it is defined for both Release and Debug builds, which I often forget to do.
By defining it macro style before you include the relevant STL headers, or, for total coverage, in stdafx.h:
#define _SCL_SECURE_NO_WARNINGS
Both of these methods work fine but I wondered if there was any argument for favouring one over the other?
|
The /D option is generally used when you want to define it differently on different builds (so it can be changed in the makefile)
If you will "always" want it set the same way, use #define.
|
297,085
| 2,900,752
|
Is there a graphical test runner for "Google Test" ( gtest ) for windows?
|
Seems a great C++ unit testing framework. I'm just wanting something a bit more sophisticated than the console output for running the test, also something that makes it really easy to run specific tests (since gtest supports all kinds of test filtering)
If there is nothing, I'll probably roll my own
|
I opened a google code project that adds UI to google test. Runs on both Windows and Unix.
It is not a plugin to any IDE by design - I did not want to tie myself. Instead you open it in the background and press the "Go" button whenever you want to run.
As of this writing V1.2.1 is out and you are invited to give it a try.
https://github.com/ospector/gtest-gbar
|
297,112
| 297,175
|
how do i use python libraries in C++?
|
I want to use the nltk libraries in c++.
Is there a glue language/mechanism I can use to do this?
Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.
Thanks
|
You can also try the Boost.Python library; which has this capability. This library is mainly used to expose C++ to Python, but can be used the other way around.
|
297,323
| 297,366
|
Is there any advantage to using C++/CLI over either standard C++ or C#?
|
I'm not seeing any real advantages, other than the fact that you have a C++ syntax, and with it, things like pointers and destructors.
|
If you're talking about why you would use C++/CLI over C#, I think the main reasons are that:
it might be more natural for C++ developers (though I think this is probably not true)
C++/CLI has very nice capabilities for bridging the native and managed environments (using the 'IJW' - It Just Works - technology)
I think that Herb Sutter probably gives the best overview:
A Design Rationale for C++/CLI
If you want to know why you might want to use native C++ over C#/.NET, this boils down to why you would want a managed environment (safety, easier development) over native code (absolute control, possibly speed advantages). There are arguments for each, and the answer really depends on what you want to develop and what your market might be.
|
297,822
| 297,847
|
Global instance of a class in C++
|
As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).
|
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.
// myclass.h
class MyClass {
public:
MyClass();
void foo();
// ...
};
extern MyClass g_MyClassInstance;
// myclass.cpp
MyClass g_MyClassInstance;
MyClass::MyClass()
{
// ...
}
Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.
|
298,024
| 298,038
|
How to debug code that uses boost w/o losing sanity?
|
Boost is a great set of libraries and it really boosts productivity. But debugging code that uses it is a total nightmare. Sure, stepping through twenty thousand header files can be a valuable intellectual exercise, but what if you need to do it over and over again?
Is there a developer-friendly way of just skipping the boost portion and having the debugger go straight to my code?
Visual Studio has a DebuggerStepThroughAttribute for .NET framework. Is there anything similar for native C++?
|
You can skip the boost namespace entirely by using the techniques described here. Just use something like:
boost\:\:.*=NoStepInto
... in the relevant registry entry.
However if your code gets called from within boost (e.g. through a boost::function or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for that problem...
|
298,139
| 298,268
|
Modifying controls with Form.Controls
|
I'm passing a reference of a form to a class. Within this class I believed I could use formRef->Controls["controlName"] to access properties on the control.
This works for a few labels, but on a button I receive a "Object reference not set to an instance of an object." when I try to change the Text property.
Help or explanation appreciated...
|
I did this, and it's working. Could possibly be safer as I can check if the control actually exists...
array<Control^>^ id = myForm->Controls->Find("myButton", true);
id[0]->Text = "new text";
I think the reason it breaks is that the button is on another panel. I didn't think of that when I posted. The new solution will search all children too, so it's an improvement.
|
298,257
| 298,262
|
ms c++ get pid of current process
|
Parts of my application are in C++ under windows. I need the process id for the current process. Any thoughts?
|
The GetCurrentProcessId function will do this.
|
298,577
| 298,590
|
Overriding a member variable in C++
|
I have run into a bit of a tricky problem in some C++ code, which is most easily described using code. I have classes that are something like:
class MyVarBase
{
}
class MyVar : public MyVarBase
{
int Foo();
}
class MyBase
{
public:
MyBase(MyVarBase* v) : m_var(v) {}
virtual MyVarBase* GetVar() { return m_var; }
private:
MyVarBase* m_var;
}
I also have a subclass of MyBase that needs to have a member of type MyVar because it needs to call Foo. Moving the Foo function into MyVarBase is not an option. Does it make sense to do this:
class MyClass : public MyBase
{
public:
MyClass(MyVar* v) : MyBase(v), m_var(v) {}
MyVar* GetVar() { return m_var; }
private:
MyVar* m_var;
}
This seems to work but looks really bad and I'm not sure if it's going to cause a memory leak or break a copy constructor. My other options might be to name the MyVar variable in MyClass something else but have it be equal to the m_var pointer in the base, or to templatise MyBase on the MyVar type.
All these options don't seem ideal so I wanted to know if anyone else has run into a situation like this and if there is a good way to make it work.
|
The correct way to do this is to have the variable only in the base class. As the derived class knows it must be of dynamic type MyVar, this is totally reasonable:
class MyClass : public MyBase
{
public:
MyClass(MyVar* v) : MyBase(v) {}
MyVar* GetVar() { return static_cast<MyVar*>(MyBase::GetVar()); }
}
Since MyVar is derived from MyVarBase, the different return-types of GetVar would still work if GetVar was virtual (as is the case here). Note that with that method, there must be no function in MyBase that can reset the pointer to something different, obviously.
Note that static_cast is the right cast in that case. Using dynamic_cast, as proposed by one commenter, will tell the readers and users of GetVar that MyBase::GetVar() could return a pointer to an object not of type MyVar. But that doesn't reflect our intention, as you only ever pass MyVar. To be consequent is the most important thing in software development. What you could do is to assert it is non-null. It will abort at runtime with an error-message in debug-builds of your project:
MyVar* GetVar() {
assert(dynamic_cast<MyVar*>(MyBase::GetVar()) != 0);
return static_cast<MyVar*>(MyBase::GetVar());
}
|
298,708
| 298,713
|
Debugging with command-line parameters in Visual Studio
|
I'm developing a C++ command-line application in Visual Studio and need to debug it with command-line arguments. At the moment I just run the generated EXE file with the arguments I need (like this program.exe -file.txt) , but this way I can't debug. Is there somewhere I can specify the arguments for debugging?
|
Yes, it's in the Debugging section of the properties page of the project.
In Visual Studio since 2008: right-click the project, choose Properties, go to the Debugging section -- there is a box for "Command Arguments". (Tip: not solution, but project).
|
299,267
| 299,298
|
Image scaling and rotating in C/C++
|
What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I should get a new image of size 0.68*1024 x 0.68*2048. some pixels will be collapsed onto each other. And, if I scale by a factor of say 3.15, I would get a larger image with pixels being duplicated. So, what's the best way to accomplish this?
Next, I would like to be able to rotate an image by an arbitrary angle, in the range of 0 to 360 degrees (0 - 2Pi). Cropping of the image after rotating isn't an issue. What would be the best way to do this?
|
There is no simple way of accomplishing this. Neither scaling nor rotating are trivial processes.
It is therefore advisable to use a 2d imaging library. Magick++ can be an idea as divideandconquer.se point out, but there are others.
|
299,761
| 300,753
|
CUDA: Wrapping device memory allocation in C++
|
I'm starting to use CUDA at the moment and have to admit that I'm a bit disappointed with the C API. I understand the reasons for choosing C but had the language been based on C++ instead, several aspects would have been a lot simpler, e.g. device memory allocation (via cudaMalloc).
My plan was to do this myself, using overloaded operator new with placement new and RAII (two alternatives). I'm wondering if there are any caveats that I haven't noticed so far. The code seems to work but I'm still wondering about potential memory leaks.
The usage of the RAII code would be as follows:
CudaArray<float> device_data(SIZE);
// Use `device_data` as if it were a raw pointer.
Perhaps a class is overkill in this context (especially since you'd still have to use cudaMemcpy, the class only encapsulating RAII) so the other approach would be placement new:
float* device_data = new (cudaDevice) float[SIZE];
// Use `device_data` …
operator delete [](device_data, cudaDevice);
Here, cudaDevice merely acts as a tag to trigger the overload. However, since in normal placement new this would indicate the placement, I find the syntax oddly consistent and perhaps even preferable to using a class.
I'd appreciate criticism of every kind. Does somebody perhaps know if something in this direction is planned for the next version of CUDA (which, as I've heard, will improve its C++ support, whatever they mean by that).
So, my question is actually threefold:
Is my placement new overload semantically correct? Does it leak memory?
Does anybody have information about future CUDA developments that go in this general direction (let's face it: C interfaces in C++ s*ck)?
How can I take this further in a consistent manner (there are other APIs to consider, e.g. there's not only device memory but also a constant memory store and texture memory)?
// Singleton tag for CUDA device memory placement.
struct CudaDevice {
static CudaDevice const& get() { return instance; }
private:
static CudaDevice const instance;
CudaDevice() { }
CudaDevice(CudaDevice const&);
CudaDevice& operator =(CudaDevice const&);
} const& cudaDevice = CudaDevice::get();
CudaDevice const CudaDevice::instance;
inline void* operator new [](std::size_t nbytes, CudaDevice const&) {
void* ret;
cudaMalloc(&ret, nbytes);
return ret;
}
inline void operator delete [](void* p, CudaDevice const&) throw() {
cudaFree(p);
}
template <typename T>
class CudaArray {
public:
explicit
CudaArray(std::size_t size) : size(size), data(new (cudaDevice) T[size]) { }
operator T* () { return data; }
~CudaArray() {
operator delete [](data, cudaDevice);
}
private:
std::size_t const size;
T* const data;
CudaArray(CudaArray const&);
CudaArray& operator =(CudaArray const&);
};
About the singleton employed here: Yes, I'm aware of its drawbacks. However, these aren't relevant in this context. All I needed here was a small type tag that wasn't copyable. Everything else (i.e. multithreading considerations, time of initialization) don't apply.
|
I would go with the placement new approach. Then I would define a class that conforms to the std::allocator<> interface. In theory, you could pass this class as a template parameter into std::vector<> and std::map<> and so forth.
Beware, I have heard that doing such things is fraught with difficulty, but at least you will learn a lot more about the STL this way. And you do not need to re-invent your containers and algorithms.
|
300,091
| 300,108
|
Preferred namespace syntax for source files
|
Assuming a class called Bar in a namespace called foo, which syntax do you prefer for your source (.cpp/.cc) file?
namespace foo {
...
void Bar::SomeMethod()
{
...
}
} // foo
or
void foo::Bar::SomeMethod()
{
...
}
I use namespaces heavily and prefer the first syntax, but when adding code using the Visual Studio Class Wizard (WM_COMMAND handlers, etc.) the auto-generated code uses the second. Are there any advantages of one syntax over the other?
|
I would decline the first (edit : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:
namespace bar {
struct foo { void f(); };
}
namespace baz {
struct foo { void f(); };
}
using namespace bar;
using namespace baz;
void foo::f() { // which foo??
}
Because it looks in the current scope (there it is the global scope), it finds two foo's, and tells you the reference to it is ambiguous.
Personally i would do it like this:
namespace foo {
void Bar::SomeMethod() {
// something in here
}
}
It's also not clear from only looking at the definition of SomeMethod to which namespace it belongs, but you have a namespace scope around it and you can easily look it up. Additionally, it is clear now that Bar refers to namespace foo.
The second way you show would be too much typing for me actually. In addition, the second way can cause confusion among new readers of your code: Is foo the class, and Bar a nested class of it? Or is foo a namespace and Bar the class?
|
300,208
| 300,225
|
How does one execute a no-op in C/C++?
|
for the following:
( a != b ) ? cout<<"not equal" : cout<<"equal";
suppose I don't care if it's equal, how can I use the above statement by substituting cout<<"equal" with a no-op.
|
If it really is for a ternary operator that doesn't need a second action, the best option would be to replace it for an if:
if (a!=b) cout << "not equal";
it will smell a lot less.
|
300,662
| 300,693
|
How do you insert with a reverse_iterator
|
I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?
This works: (of course it does)
std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);
This doesn't work: (what should I do instead?)
std::list<int> l;
std::list<int>::reverse_iterator reverse = l.rbegin();
l.insert(reverse, 10);
|
l.insert(reverse.base(), 10); will insert '10' at the end, given your definition of the 'reverse' iterator. Actually, l.rbegin().base() == l.end().
|
300,669
| 300,680
|
launch app, capture stdout and stderr in c++
|
How do I launch an app and capture the output via stdout and maybe stderr?
I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build.
I can't find the system() function, but I found the CreateProcess() function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout. I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?
|
In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then:
program arg1 arg2 >/tmp/log.file 2>&1
This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation (hieroglyph) '2>&1' at the end sends stderr (file descriptor 2) to the same place that stdout (file descriptor 1) is going. Note that the sequence of operations is important; if you reverse them, then standard error will go to where standard output was going, and then standard output (but not standard error) will be redirected to the file.
The choice of file name shown is abysmal for numerous reasons - you should allow the user to choose the directory, and probably should include the process ID or time stamp in the file name.
LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S)
program arg1 arg2 >$LOG 2>&1
In C++, you can use the system() function (inherited from C) to run processes. If you need to know the file name in the C++ program (plausible), then generate the name in the program (strftime() is your friend) and create the command string with that file name.
(Strictly, you also need getenv() to get $TMPDIR, and the POSIX function getpid() to get the process ID, and then you can simulate the two-line shell script (though the PID used would be of the C++ program, not the launched shell).
You could instead use the POSIX popen() function; you'd have to include the '2>&1' notation in the command string that you create to send the standard error of the command to the same place as standard output goes, but you would not need a temporary file:
FILE *pp = popen("program arg1 arg2 2>&1", "r");
You can then read off the file stream. I'm not sure whether there's a clean way to map a C file stream into a C++ istream; there probably is.
|
300,808
| 300,837
|
C++: how to cast 2 bytes in an array to an unsigned short
|
I have been working on a legacy C++ application and am definitely outside of my comfort-zone (a good thing). I was wondering if anyone out there would be so kind as to give me a few pointers (pun intended).
I need to cast 2 bytes in an unsigned char array to an unsigned short. The bytes are consecutive.
For an example of what I am trying to do:
I receive a string from a socket and place it in an unsigned char array. I can ignore the first byte and then the next 2 bytes should be converted to an unsigned char. This will be on windows only so there are no Big/Little Endian issues (that I am aware of).
Here is what I have now (not working obviously):
//packetBuffer is an unsigned char array containing the string "123456789" for testing
//I need to convert bytes 2 and 3 into the short, 2 being the most significant byte
//so I would expect to get 515 (2*256 + 3) instead all the code I have tried gives me
//either errors or 2 (only converting one byte
unsigned short myShort;
myShort = static_cast<unsigned_short>(packetBuffer[1])
|
Well, you are widening the char into a short value. What you want is to interpret two bytes as an short. static_cast cannot cast from unsigned char* to unsigned short*. You have to cast to void*, then to unsigned short*:
unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]));
Now, you can dereference p and get the short value. But the problem with this approach is that you cast from unsigned char*, to void* and then to some different type. The Standard doesn't guarantee the address remains the same (and in addition, dereferencing that pointer would be undefined behavior). A better approach is to use bit-shifting, which will always work:
unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];
|
300,986
| 300,995
|
When should you not use virtual destructors?
|
Is there ever a good reason to not declare a virtual destructor for a class? When should you specifically avoid writing one?
|
There is no need to use a virtual destructor when any of the below is true:
No intention to derive classes from it
No instantiation on the heap
No intention to store with access via a pointer to a superclass
No specific reason to avoid it unless you are really so pressed for memory.
|
301,008
| 301,015
|
What is a "query parameter" in C++?
|
We were using stringstream to prepare select queries in C++. But we were strongly advised to use QUERY PARAMETERS to submit db2 sql queries to avoid using of stringstream. Can anyone share what exactly meant by query parameter in C++? Also, share some practical sample code snippets.
Appreciate the help in advance.
Edit: It is stringstream and not strstream.
Thanks,
Mathew Liju
|
I suspect this refers to parameterized queries in general, rather than constructing the query in a string, they supply sql variables (or parameters) and then pass those variables separately. These are much better for handling SQL Injection Attacks. To illustrate with an example:
"SELECT * FROM Customers WHERE CustomerId = " + _customerId;
Is bad, while this:
"SELECT * FROM Customers where CustomerId = @CustomerId"
is good. The catch is that you have to add the parameters to the query object (I don't know how this is done in C++.
References to other questions:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Stored Procedures vs Parameterized Queries
Wild Wild Web:
http://www.justsoftwaresolutions.co.uk/database/database-tip-use-parameterized-queries.html
|
301,024
| 308,167
|
Validate Authenticode signature on EXE - C++ without CAPICOM
|
I'm writing a function for an installer DLL to verify the Authenticode signature of EXE files already installed on the system.
The function needs to:
A) verify that the signature is valid.
B) verify that the signer is our organization.
Because this is in an installer, and because this needs to run on older Win2k installations, I don't want to rely on CAPICOM.dll, as it may not be on the target system.
The WinVerifyTrust API works great to solve (A).
I need to find a way to compare a known certificate (or properties therein) to the one that signed the EXE in question.
|
You should use CryptQueryObject.
This KB-article demonstrates the use: How To Get Information from Authenticode Signed Executables.
To the commenter that asked about how to do it without the Windows-APIs, I am not aware of any library that can do it, but the format is documented here: Windows Authenticode Portable Executable Signature Format
|
301,054
| 301,098
|
How can I determine if a Win32 thread has terminated?
|
How can I determine if a Win32 thread has terminated?
The documentation for GetExitCodeThread warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.
Thanks for the help! :)
|
MSDN mentions that "When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object".
So, you can check for whether a thread has terminated by checking the state of the thread handle - whether it's signaled or not:
DWORD result = WaitForSingleObject( hThread, 0);
if (result == WAIT_OBJECT_0) {
// the thread handle is signaled - the thread has terminated
}
else {
// the thread handle is not signaled - the thread is still alive
}
|
301,129
| 301,140
|
How to create database connectivity through C++
|
In C++, how can I establish an SQL connection to store data in an SQL database?
|
You should have a look at C preprocessors that exists traditionaly with databases (ecpg for postgres, Pro*C for oracle ... which lets you embed straight SQL directly in your source files) or an orginal system for mysql. ECPG will do with C++, that is/was not the case for some other preprocessors ...
|
301,144
| 301,151
|
From where I can download Turbo C++ setup
|
From where I can download Turbo C++ setup, the one with blue srceen which we used in our academics..
|
From the museum (legal)
|
301,203
| 301,274
|
Extract C++ template parameters
|
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.
For example:
typedef std::bitset<16> WordSet;
Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in g++.
|
It's not possible in general to pick arbitrary template parameters.
However, the usual way you do it is this:
template<int N>
struct foo {
static const int value = N;
};
and for types
template<typename T>
struct foo {
typedef T type;
};
You can access it then as foo<39>::value or foo<int>::type.
If you have a particular type, you can use partial template specialization:
template<typename>
struct steal_it;
template<std::size_t N>
struct steal_it< std::bitset<N> > {
static const std::size_t value = N;
};
The same principle is possible for type parameters too, indeed. Now you can pass any bitset to it, like steal_it< std::bitset<16> >::value (note to use size_t, not int!). Because we have no variadic many template paramters yet, we have to limit ourself to a particular parameter count, and repeat the steal_it template specializations for count from 1 up to N. Another difficulty is to scan types that have mixed parameters (types and non-types parameters). This is probably nontrivial to solve.
If you have not the type, but only an object of it, you can use a trick, to still get a value at compile time:
template<typename T>
char (& getN(T const &) )[steal_it<T>::value];
int main() {
std::bitset<16> b;
sizeof getN(b); // assuming you don't know the type, you can use the object
}
The trick is to make the function template auto-deduce the type, and then return a reference to a character array. The function doesn't need to be defined, the only thing needed is its type.
|
301,241
| 301,270
|
paste on site, syntax highlighting
|
I am getting a web host and i have projects with teammats. I thought it be a nice idea to have my own paste site that has no expiry date on paste (i know http://pastie.org/ exist) and other things. i wanted to know. Whats a simple highlight lib i can use on code? i would be only using C/C++.
|
The question is tagged "php" but you "would be only using C/C++"?
A PHP solution is GeSHi.
|
301,279
| 301,282
|
How do I implement simple copy/paste functionality in an mfc CListCtrl?
|
Is this really the easiest way to do this?
http://simplesamples.info/MFC/Clipboard.php
|
Is your list the source or destination? Do you need to copy/paste to or from something else like Excel? Do you expect some specific formatting? It all depends.
Edit:
If you are moving things out to simple text, your link looks good. See Clipboard: Using the Windows Clipboard too.
|
301,357
| 301,612
|
delete and delete [] the same in Visual C++?
|
I know that I am supposed to use delete [] after I use new [], so using auto_ptr with new [] is not such a bright idea.
However, while debugging delete [] (using Visual Studio 2005), I noticed that the call went into a function that looked like this:
void operator delete[]( void * p )
{
RTCCALLBACK(_RTC_Free_hook, (p, 0))
operator delete(p);
}
Does this mean, the [] syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?
|
Consider this code:
class DeleteMe
{
public:
~DeleteMe()
{
std::cout << "Thanks mate, I'm gone!\n";
}
};
int main()
{
DeleteMe *arr = new DeleteMe[5];
delete arr;
return 0;
}
If you run that in VS2005 it will print:
Thanks mate, I'm gone!
If you change main() to correctly adhere to the C++ standard:
int main()
{
DeleteMe *arr = new DeleteMe[5];
delete[] arr;
return 0;
}
It will print:
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Don't shoot yourself in the foot. VS2005 will NOT do the correct thing if you mismatch different flavors of new/delete. Neither will any other C++ standard conformant compiler.
There's some compiler magic going on around operator new and operator delete (and their different flavors), basically the call to the ctors and dtors are added behind the scenes. This magic depends on those small brackets [], so don't lose them or you'll lose the magic.
|
301,526
| 326,610
|
Ant -> Nant -> Visual Studio 2005 Build
|
I am working on a big C++ project. It is building using single Ant script which makes possible to compile the same source targeting more than one platform and compiler.
But, I have to work only for Windows platform and Visual Studio 2005 C++ compiler. It would be really nice if I could write code and compile in Visual Studio, instead of using Notepad++ and Ant scripts, as I do now.
I tried to install Nant and Nant addin for Visual Studio 2005, and to use existing Ant script, but it seems that Ant script cannot be used as a Nant script.
Is there any way to convert Ant script to Nant? Is any other approach to the problem at all, or I must create Visual Studio solution and projects manually?
I would try to avoid such solution because I have a bunch of tests that I don't know how to use in that case.
|
To my knowledge, there is no automatic way of converting Ant script to NAnt. However, since NAnt is based off of the Ant the conversion process would not be too far from the original, as long as the tasks are the "core" ones. Possibly an XSLT translation could be made on the Ant scripts to convert to NAnt as both are XML. If one were to go down this path the conversion should be done dynamically based of the original Ant scripts, so that only one set of scripts would have to be maintained.
If you would like to write and compile your C++ code inside of Visual Studio it's tough to beat the functionality that is built in with the IDE. However, this requires creating project files though. Otherwise, it seems that one would risk fighting an uphill battle with the tool.
One option for the tests would be to call out through a custom build step to run them.
|
301,553
| 301,980
|
Returning a value from a method in an ActiveX control
|
I'm creating an ActiveX control that will be used in web pages to query the current installed version of a 3rd party software on the client machine. The control only needs to expose a single method - GetVersion - that returns the version as an integer. I'm very inexperienced with ActiveX, and I'm having problems with something as simple as correctly returning values from methods. If i use the following declaration in the IDL:
[id(1)] void GetVersion();
Paired with the following implementation:
BEGIN_DISPATCH_MAP(CDetectorCtrl, COleControl)
DISP_FUNCTION_ID(CDetectorCtrl, "GetVersion", 1, GetVersion, VT_EMPTY, VTS_NONE)
END_DISPATCH_MAP()
void CDetectorCtrl::GetVersion()
{
MessageBox(L"Test");
}
I can invoke the method from HTML and see my MessageBox just fine.
But if I change the definition/code to:
[id(1)] int GetVersion();
and
BEGIN_DISPATCH_MAP(CDetectorCtrl, COleControl)
DISP_FUNCTION_ID(CDetectorCtrl, "GetVersion", 1, GetVersion, VT_INT, VTS_NONE)
END_DISPATCH_MAP()
int CDetectorCtrl::GetVersion()
{
MessageBox(L"Test");
return 1337;
}
I get a crash when I invoke the method from HTML.
|
Asked and answered...
The problem appeared to a missing AFX_MANAGE_STATE in the method itself:
LONG CDetectorCtrl::GetVersion(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return 1337;
}
|
301,555
| 301,692
|
How to attach to process using VC6 on win 2003?
|
The 'attach to process' dialogue box on VC6 running on win 2003 (I believe vista as well) has no processes to attach to in it... I've tried logging on as an administrator and running as an administrator but no luck. Any other ideas?
|
There is a bug that's been fixed in SP 4. See this for details.
|
301,576
| 301,587
|
How do I tell valgrind to memcheck forked processes?
|
I have a process x that I want to check for leaks with valgrind. The problem is that x is run by y, and y in turn is run by z. I can't run x standalone because y and z setup the environment for x, such as environment variables, command line switches, files needed by x etc.
Is there any way I can tell valgrind to run on z but to follow any forks it finds and report them too?
Is there any way I can tell valgrind to follow any forks but only report on the process named x?
Is there any way I can tell valgrind to attach to already-running process, the way I can do with gdb?
I don't know if this matters, but I'm running under SuSE64 linux and valgrind-2.4.0.
Thanks!
|
Valgrind follows forked processes when given the --trace-children=yes option.
You should be able to achieve this by using suitable filters.
No. Valgrind hooks into the module loading code using LD_PRELOAD, so attaching to a running process is not possible.
|
301,586
| 301,907
|
Difference between using #include<filename> and #include<filename.h> in C++
|
What is the difference between using #include<filename> and #include<filename.h> in C++? Which of the two is used and why is it is used?
|
C++ only include-files not found in the C standard never used filename.h . Since the very first C++ Standard came out (1998) they have used filename for their own headers.
Files inherited by the C Standard became cfilename instead of filename.h. The C files inherited used like filename.h are deprecated, but still part of the C++ standard.
The difference is that names not defined as macros in C are found within namespace std:: in cfilename in C++, while names in filename.h are within the global namespace scope. So you will find ::size_t in stddef.h, and std::size_t in cstddef. Both are Standard C++, but use of ::size_t is deprecated (See Annex D of the C++ Standard).
Now those were the difference.
Why would you use `filename.h` ?
Compatibility with C compilers
Compatibility with very old C++ compilers
Why should you use `cfilename` ?
Names are within namespace std:: . No name-clashes anymore.
New C++ features (e.g. overloaded math functions for float, long)
C Compatibility Headers (filename.h) could disappear in future.
|
301,622
| 301,640
|
C++ enum to unsigned int comparison
|
I found this in the code I'm working on at the moment and thought it was the cause of some problems I'm having.
In a header somewhere:
enum SpecificIndexes{
//snip
INVALID_INDEX = -1
};
Then later - initialization:
nextIndex = INVALID_INDEX;
and use
if(nextIndex != INVALID_INDEX)
{
//do stuff
}
Debugging the code, the values in nextIndex didn't quite make sence (they were very large), and I found that it was declared:
unsigned int nextIndex;
So, the initial setting to INVALID_INDEX was underflowing the unsigned int and setting it to a huge number. I assumed that was what was causing the problem, but looking more closely, the test
if(nextIndex != INVALID_INDEX)
Was behaving correctly, i.e, it never executed the body of the if when nextIndex was the "large +ve value".
Is this correct? How is this happening? Is the enum value being implicitly cast to an unsigned int of the same type as the variable, and hence being wrapped in the same way?
|
Yes to everything.
It is valid code, it is also commonly used library-side C++ code, more so in modern C++ (it is strange when you see it the first time but its a very common pattern in reality).
Then enums are signed ints, but they get implicitly cast into unsigned ints, now this depending on your compiler might give a warning, but its still very commonly used, however you should explicitly cast to make it clear to maintainers.
|
301,655
| 301,762
|
C++ Visual Studio Runtime Error
|
Can anyone explain to me what this means?
"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."
|
When calling a function, the compiler has to push some arguments on the stack, or put them in some registers. The function body will change some memory location (or a register) to contain the return value. Then it will return to a block of code at a location stored 'somewhere' on the stack.
The calling convention specifies the concrete details: e.g. first push the return address, then push arguments (input or output) on the stack from left to right, then execute the function, pop the arguments off again, then pop the return address and jump to that location.
If the caller does this differently than the function expects, things can go wrong (return location is not at the expected stack position).
ESP is typically the register containing the address of the current stack frame. This register is used in combination with indexes to obtain arguments in the function body. When returning, the stack top is typically reset to ESP, and the processor jumps to the location at e.g. ESP+1.
Things that may cause this to happen:
someone wrote over the values of the stack and changed the return location (e.g. buffer overflow)
the caller had a different calling convention than the callee
|
301,892
| 301,984
|
Printing the stack trace in C++ (MSVC)?
|
In my C++ application (developed with Visual Studio 2003) and Qt4, I'd like to print the stack trace from a specific line of code, either to the console output or into a file.
What would it take ?
Is Qt of any help to do this ?
|
StackWalker by Jochen Kalmbach [MVP VC++] and available on codeproject is probably the easiest way to do this. It wraps up all of the details of dealing with the underlying StackWalk64 API.
|
301,959
| 301,990
|
Vector iterator not dereferencable
|
I have an abstract base class called Shape from which both Circle and Rectangle are derived, but when I execute the following code in VS 2005 I get the error Debug assertion failed. At the same time I have not overloaded == operator in any class
Expression:Vector iterator not dereferencable, what is the reason for this.
vector<Shape*> s1;
s1.push_back(new Circle(point(1,2),3));
s1.push_back(new Circle(point(4,3),5));
s1.push_back(new Rectangle(point(1,1),4,5));
vector<Shape*> s2(s1);
reverse(s1.begin(),s1.end());
(*find(s1.begin(),s1.end(),new Circle(point(1,2),3)))->move(point(10,20));
|
Simple :
find fails since your newly created Circle can't be found in the vector with comparing Shape *
a failed find returns the end iterator which is not deferencable as caught by a Debug assertion
For it to work like you want, you do need to compare Shape, not Shape*
As pointed out in other answers, boost::ptr_vector is an easy way to achieve this.
|
302,208
| 302,257
|
How do you build the x64 Boost libraries on Windows?
|
I've built the x86 Boost libraries many times, but I can't seem to build x64 libraries. I start the "Visual Studio 2005 x64 Cross Tools Command Prompt" and run my usual build:
bjam --toolset=msvc --build-type=complete --build-dir=c:\build install
But it still produces x86 .lib files (I verified this with dumpbin /headers).
What am I doing wrong?
|
You need to add the address-model=64 parameter.
Look e.g. here.
|
302,314
| 302,328
|
How do I change the ACLs on a registry key? (C++)
|
I need to delete a regsitry key. It has a deny ACL on Set Value (I need this permission to delete it).
How do I change the ACLs in C++?
|
You could use RegSetKeySecurity to adjust the security settings and then delete the key as usual.
|
302,329
| 510,616
|
Firefox plugin crashes in Chrome
|
From what I gather, Google Chrome can run browser plugins written using NPAPI.
I've written one that does its job just fine in Firefox, but makes Chrome crash and burn as soon as you embed it on a page. I don't even have to call any of my methods, embedding is enough to cause a crash.
How do I debug this? I tried attaching the debugger to chrome but the stack traces I get are deep down in Chrome itself and like I said, none of "my" actual code is being run, but supposedly just the NPAPI init code.
I'd appreciate some pointers.
|
As it turns out, part of the initialization code from the old NPAPI plugin example I was using caused the crash. I'm sorry to say I solved this quite a while back and can't seem to locate the specific modifications I made to fix it in the version control history. Anyway, my problem is fixed and was caused by me being stupid and blindly trusting the example code.
|
302,742
| 302,898
|
Reading a file of mixed data into a C++ string
|
I need to use C++ to read in text with spaces, followed by a numeric value.
For example, data that looks like:
text1
1.0
text two
2.1
text2 again
3.1
can't be read in with 2 "infile >>" statements. I'm not having any luck with getline
either. I ultimately want to populate a struct with these 2 data elements. Any ideas?
|
The standard IO library isn't going to do this for you alone, you need some sort of simple parsing of the data to determine where the text ends and the numeric value begins. If you can make some simplifying assumptions (like saying there is exactly one text/number pair per line, and minimal error recovery) it wouldn't be too bad to getline() the whole thing into a string and then scan it by hand. Otherwise, you're probably better off using a regular expression or parsing library to handle this, rather than reinventing the wheel.
|
302,768
| 302,816
|
Why does Visual C++ not hit a breakpoint in, or step through a specific function?
|
I have the following:
classA::FuncA()
{
... code
FuncB();
... code
}
classA::FuncB(const char *pText)
{
SelectObject(m_hDC, GetStockObject ( SYSTEM_FONT));
wglUseFontBitmaps(m_hDC, 0, 255, 1000);
glListBase(1000);
glCallLists(static_cast<GLsizei>(strlen(pText)), GL_UNSIGNED_BYTE, pText);
}
I can hit breakpoints anywhere in FuncA. If I try to step into FuncB, it steps over. It will accept a breakpoint in FuncB, but never hits it. I know it is executing FuncB, because I can put a MessagBox() call in FuncB and get the message box.
I'm new to VS2005 after a few years away from extensive VC6 usage. The one situation like this I recall from my VC6 days, is if symbol information is not available. However, in this case both functions are in the same file, so the symbol information must be correct. Also in that case I think you couldn't even set the breakpoint.
I've tried all the silly voodoo like rebuilding the whole solution.
What stupid thing am I overlooking?
EDIT: Added code for FuncB in response to comment about it possibly being essentially inline-able. (It's just the exact sample code from MSDN for wglUseFontBitmaps [minus comments here]). I don't see how inlining that would impede stepping through each call.
|
Make sure all compiler optimizations are disabled (/Od). Compiler optimization can cause problems with debugger breakpoints.
|
302,914
| 302,932
|
CRC32 C or C++ implementation
|
I'm looking for an implementation of CRC32 in C or C++ that is explicitly licensed as being no cost or public domain. The implementation here seems nice, but the only thing it says about the license is "source code", which isn't good enough. I'd prefer non LGPL so I don't have to fool around with a DLL (my app is closed source). I saw the adler32 implementation in zlib, but I'm checking small chunks of data, which adler is not good for.
|
Use the Boost C++ libraries. There is a CRC included there and the license is good.
|
303,243
| 303,265
|
Store 2D points for quick retrieval of those inside a rectangle
|
I have a large number of 2D points and I want to quickly get those that lie in a certain rectangle.
Let's say a '.' is any point and 'X' is a point I want to find inside a rectangle which has 'T' as TopLeft and 'B' as BottomRight points:
. . . . . .
. T-----+ .
. | X X | .
. +-----B .
. . . . . .
I have tried a std::set with a sort functor which sorts the TopLeft point at the beginning and the BottomRight at the end of the set. When sorting by X value first, this would result in the following points being found.
. . . . . .
. T-----+ .
X | X X | X
. +-----B .
. . . . . .
This means I would have to check each found point, whether it really is inside the rectangle. Not really good.
What would be a better way to do this?
My language is C++ (Windows) and I have the STL as well as boost available.
Update
Having read the answers so far, I noticed that I haven't accounted for all parameters of my problem: There is not one fixed rectangle.
Rectangles can be set by the user at runtime. This means sorting the set of points promises to be more efficient than a linear search through all points as suggested by Artelius before this update.
I will still give it a try, though! I don't expect the user to set a rectangle very frequent. So regarding the implementation effort it might show up to be a good solution for me.
|
You could store the points in a spatial index using quad or r-trees. Then given the rectangle you could find all the nodes of the tree that overlap it, you would then have to compare each point in this subset to see if it falls in the rectangle.
In essence, the spatial tree helps you prune the search space.
You might be able to use a simpler solution, such as partitioning the points in ranges. Say where x is from 0,10 as one range, 11,20 as another. Any solution that lets you prune the search space will help.
|
303,371
| 303,402
|
what's the easiest way to generate xml in c++?
|
I've used boost serialization but this doesn't appear to allow me to generate xml that conforms to a particular schema -- it seems it's purpose was to just to persist a class's state.
Platform: linux
What do you guys use to generate NOT parse xml?
So far I'm going down Foredecker's route of just generating it myself -- it's not a large document but I really shouldn't be having this much trouble finding a decent library to generate it correctly.
As for boost, the things that I would like to be able to do is set the node names, set attributes in my nodes, and get rid of all the extra crap that comes with it as I don't really care about having to put my document back into that class.
|
Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file.
Once saved - you really should then validate with a schema before committing it our shipping it off.
For one of our projects we have a very simple set of templates for managing begin/end tags and attributes. These each have a stream output operator. This makes it very easy to generate the source XML and debug. This makes the structure of the XML generation code look very much like the XML itself.
One advantage of this is that you can generate large amounts of XML efficiently if streaming to a file. You will pay the validation costs later (presumably at a better time for an expensive operation).
The downside of this technique is that it is essentially output only. It is not suitable for creating then consuming XML dynamically.
|
303,405
| 303,412
|
Implementing threads using C++
|
I have an API call in my application where I am checking the time taken for a single call. I have put this in a FOR loop and using 10000 calls to get the average times of all calls. Now the issue which came up was that the actual application using the API, is multi-threaded. If I wish to make my application also do the same, how would I go about doing this?
The platform is REL and my aim is to send multiple calls in the same time with either the same parameters or different parameters. Can this be implemented in C++ and if so, what library functions to use and can an example be provided for the same?
|
Probably the best C++ library to use for threading is the thread library in Boost, but like all C++ threading, you will be forced to manually do your synchronization. You will need to use mutex and lock types to make it work properly. Your question isn't very clear, so I can't really help you any more (though I think you don't actually need threading, but I could be completely misunderstanding).
|
303,562
| 306,053
|
C++ format macro / inline ostringstream
|
I'm trying to write a macro that would allow me to do something like: FORMAT(a << "b" << c << d), and the result would be a string -- the same as creating an ostringstream, inserting a...d, and returning .str(). Something like:
string f(){
ostringstream o;
o << a << "b" << c << d;
return o.str()
}
Essentially, FORMAT(a << "b" << c << d) == f().
First, I tried:
1: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << items)).str()
If the very first item is a C string (const char *), it will print the address of the string in hex, and the next items will print fine. If the very first item is an std::string, it will fail to compile (no matching operator <<).
This:
2: #define FORMAT(items) \
((std::ostringstream&)(std::ostringstream() << 0 << '\b' << items)).str()
gives what seems like the right output, but the 0 and \b are present in the string of course.
The following seems to work, but compiles with warnings (taking address of temporary):
3: #define FORMAT(items) \
((std::ostringstream&)(*((std::ostream*)(&std::ostringstream())) << items)).str()
Does anyone know why 1 prints the address of the c-string and fails to compile with the std::string? Aren't 1 and 3 essentially the same?
I suspect that C++0x variadic templates will make format(a, "b", c, d) possible. But is there a way to solve this now?
|
You've all pretty much nailed this already. But it's a little challenging to follow. So let me take a stab at summarizing what you've said...
That difficulties here are that:
We are playing with a temporary ostringstream object, so taking addresses is contra-indicated.
Because it's a temporary, we cannot trivially convert to an ostream object through casting.
Both the constructor [obviously] and str() are class ostringstream methods.
(Yes, we need to use .str(). Using the ostringstream object directly would wind up invoking ios::operator void*(), returning a pointer-like good/bad value and not a string object.)
operator<<(...) exists as both inherited ostream methods and global functions. In all cases it returns an ostream& reference.
The choices here for ostringstream()<<"foo" are the inherited method ostream::operator<<(void* ) and the global function operator<<(ostream&,const char* ). The inherited ostream::operator<<(void* ) wins out because we can't convert to an ostream object reference to invoke the global function. [Kudos to coppro!]
So, to pull this off, we need to:
Allocate a temporary ostringstream.
Convert it to an ostream.
Append data.
Convert it back to an ostringstream.
And invoke str().
Allocating: ostringstream().
Converting: There are several choices. Others have suggested:
ostringstream() << std::string() // Kudos to *David Norman*
ostringstream() << std::dec // Kudos to *cadabra*
Or we could use:
ostringstream() . seekp( 0, ios_base::cur )
ostringstream() . write( "", 0 )
ostringstream() . flush()
ostringstream() << flush
ostringstream() << nounitbuf
ostringstream() << unitbuf
ostringstream() << noshowpos
Or any other standard manipulator. [#include <iomanip>] Reference: See "Insert data with format" 1/3 of the way down on this webpage.
We cannot use:
operator<<( ostringstream(), "" )
(ostream &) ostringstream()
Appending: Straightforward now.
Converting back: We could just use (ostringstream&). But a dynamic_cast would be safer. In the unlikely event dynamic_cast returned NULL (it shouldn't), the following .str() will trigger a coredump.
Invoking str(): Guess.
Putting it all together.
#define FORMAT(ITEMS) \
( ( dynamic_cast<ostringstream &> ( \
ostringstream() . seekp( 0, ios_base::cur ) << ITEMS ) \
) . str() )
References:
IOstream Library
ostringstream
ostream::operator<<()
Type Casting Tutorial
Wiki: Type Casting
.
|
303,668
| 303,695
|
Object Oriented Design help from C++ to C#
|
Hey I usually run into a situation where I will create a class that should only be instantiated by one or a few classes. In this case I would make its constructor private and make it a friend class to the objects that should be able to instantiate it. For example (in C++):
class CFoo
{
friend class CFoo;
// private ctor because only a select few classes should instantiate
private:
CFoo()
{
... Do stuff
}
}
class CBar
{
// CBar is one of the few classes that only need to use CFoo
CFoo *m_pFoo;
CBar()
{
m_pFoo = new CFoo;
}
}
So my question is: Is this stupid? Or is there a better way to achieve this? I'm especially interested in a way where it would work with C# considering the language lacks the friend keyword completely. Thanks.
|
The goal here seems to be that you cannot have a CFoo until you have a working CBar.
You could achieve the same with C# by having a private constructor for CFoo and then making a static method in CFoo that takes a CBar argument and calls said constructor and returns the new CFoo.
This would be something like the System.Drawing.Graphics.FromImage(Image image) method.
The question of why C# doesn't have the friend keyword has been covered elsewhere.
|
303,759
| 303,796
|
convert string to long long
|
I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char* to a long long type. Is there an easy way to do it?
Thanks in advance :)
|
Try _atoi64. This takes char* and returns __int64.
|
304,011
| 304,013
|
Truncate a decimal value in C++
|
What's the easiest way to truncate a C++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?
|
First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable.
But here are a couple of solutions to the problem that will probably meet your need:
Probably the better method but less efficient:
char sz[64];
double lf = 0.600000002;
sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000
double lf2 = atof(sz);
//lf == 0.600000002;
//lf2 == 0.6000
printf("%.4lf", lf2); //print 0.6000
The more efficient way, but probably less precise:
double lf = 0.600000002;
int iSigned = lf > 0? 1: -1;
unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate
lf = (((double)uiTemp)/pow(10,4) * iSigned);
|
304,088
| 304,091
|
Is C code still considered C++?
|
The comment to this answer got me wondering. I've always thought that C was a proper subset of C++, that is, any valid C code is valid C++ code by extension. Am I wrong about that? Is it possible to write a valid C program that is not valid C++ code?
EDIT: This is really similar to, but not an exact duplicate of this question.
|
In general, yes C code is considered C++ code.
But C is not a proper subset in a strict sense. There are a couple of exceptions.
Here are some valid things in C that are not valid in C++:
int *new;//<-- new is not a keyword in C
char *p = malloc(1024); //void * to char* without cast
There are more examples too, but you get the idea.
I previously wrote a more extensive answer in a similar question here.
|
304,093
| 304,169
|
Why shared_ptr has an explicit constructor
|
I was wondering why shared_ptr doesn't have an implicit constructor. The fact it doesn't is alluded to here: Getting a boost::shared_ptr for this
(I figured out the reason but thought it would be a fun question to post anyway.)
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace boost;
using namespace std;
void fun(shared_ptr<int> ptr) {
cout << *ptr << endl;
}
int main() {
int foo = 5;
fun(&foo);
return 0;
}
/* shared_ptr_test.cpp: In function `int main()':
* shared_ptr_test.cpp:13: conversion from `int*' to non-scalar type `
* boost::shared_ptr<int>' requested */
|
In this case, the shared_ptr would attempt to free your stack allocated int. You wouldn't want that, so the explicit constructor is there to make you think about it.
|
304,285
| 304,293
|
Simple Question about Visio 2007 (trying to create a simple UML diagram(C++) )?
|
I'm simply trying to create a UML diagram where I can show the header file declarations.
I to be able to display things such as:
Bitmap * getImage()
Coordinate * getCoordinates(Object o)
Stuff like that. Problem is, I can't figure out how to display pointers as return types(it only let's be choose objects from the UML diagram) or arguments. I can get around the return types by just including them in the name of the function, but I still can't find out how to display the arguments (ex: Object o listed previously) or just find a quick fix around it. I can't quick fix it the same way because Visio automatically puts a parenthesis at the end of my function (ex: Coordinate * getCoordinates(Object o) would output Coordinate * getCoordinates(Object o)()
Is there a way to enter arguments and parameters that could include pointers? Or a quick fix around it?
Thanks in advance
|
Go to the method in question in the "Operations" area of the dialog box. Then click on the "Properties" button to get the "UML Operation Properties" dialog. In there, set the "suffix" to "*".
|
304,393
| 304,406
|
How do I create a sqllite3 in-memory database?
|
One of the appropriate uses for sqlite3 is "in-memory databases". This sounds like a really useful tool for my C++ applications. Does anyone have an example of how this is done in C or C++? I'm specifically looking for a canonical way to slurp several flat-files into an in-memory database, then do some joins.
|
It's actually quite easy. Just specify ':memory:' as the database filename when opening a database using the C/C++ API. It's a special constant that the engine will recognize. The same actually works for other languages such as Python or Ruby, since they typically just wrap the C/C++ API. See http://sqlite.org/c3ref/open.html for complete details.
|
304,537
| 304,549
|
Does anyone know of a C/C++ Unix QR-Code library?
|
I'm looking for a QR-Code library for C/C++, not Java or .Net please. Anyone knows of one?
Note: There was a similar question a while back however but it didn't get
answered properly.
|
How is this one?
http://megaui.net/fukuchi/works/qrencode/index.en.html
|
304,587
| 311,187
|
Hibernate-like framework for C++
|
I am looking for database-caching framework for C++ providing the following:
Generate object/table representations via some pseudo-language (macros/templates)
Retrieve objects from DB by key when needed
LRU caching
Immediate and delayed update of DB on object update (via getter/setter methods)
|
Try LiteSQL and Hiberlite and see if they can be of use to you.
|
304,621
| 304,637
|
Screen Rotation on Pocket PC
|
I am developing an application for pocket PC which should run in landscape mode.
I wrote the function SetScreenOrientation(int angle), which rotates the screen. This function is called on application start and on application close. I want to change the screen orientation when I minimize/maximize orientation as well. To do this I edited the following function:
void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
RECT r;
GetWindowRect(&r);
RECT rstatus;
rstatus.left = 0;
rstatus.top = 0;
rstatus.right = r.right;
rstatus.bottom = TOOLBAR_HEIGHT;
m_wndStatus.MoveWindow(&rstatus, TRUE);
RECT rcamera;
rcamera.left = 0;
rcamera.top = 0;
rcamera.right = r.right;
rcamera.bottom = r.bottom - TOOLBAR_HEIGHT;
m_wndCameraView.MoveWindow(&rcamera, TRUE);
if(nType == SIZE_MAXIMIZED)
{
CScreenOrientation::SetScreenOrientation(270);
}
if(nType == SIZE_MINIMIZED)
{
CScreenOrientation::SetScreenOrientation(0);
}
}
The problem is that when I minimize the application the function is executed more than once so the screen first rotates back to 0 degrees and then it rotates to 270 degrees.
While debugging I can see that the second time the function is executed the following piece of wincore code is executed:
BOOL CWnd::OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
...
switch (lpEntry->nSig)
{
...
case AfxSig_v_u_ii:
(this->*mmf.pfn_v_u_i_i)(static_cast<UINT>(wParam), LOWORD(lParam), HIWORD(lParam));
break;
...
}
}
Does anyone know any other way to set the screen orientation on application minimize/maximize or any trick that could prevent multiple function execution?
|
For one thing, it seems likely that SetScreenOrientation is going to give you another OnSize notification, so you want to detect recursive calls and do nothing when that happens.
More importantly, how do you know what orientation the user really wants? When your application starts up you can check the orientation and save that. But if the user changed the orientation while you happened to be running, they won't be happy when you change it back. Maybe you can check notifications of system settings changes and detect if the user changed the orientation themselves.
|
304,752
| 304,783
|
How to estimate the thread context switching overhead?
|
I am trying to improve the performance of the threaded application with real-time deadlines. It is running on Windows Mobile and written in C / C++. I have a suspicion that high frequency of thread switching might be causing tangible overhead, but can neither prove it or disprove it. As everybody knows, lack of proof is not a proof of opposite :).
Thus my question is twofold:
If exists at all, where can I find any actual measurements of the cost of switching thread context?
Without spending time writing a test application, what are the ways to estimate the thread switching overhead in the existing application?
Does anyone know a way to find out the number of context switches (on / off) for a given thread?
|
While you said you don't want to write a test application, I did this for a previous test on an ARM9 Linux platform to find out what the overhead is. It was just two threads that would boost::thread::yield() (or, you know) and increment some variable, and after a minute or so (without other running processes, at least none that do something), the app printed how many context switches it could do per second. Of course this is not really exact, but the point is that both threads yielded the CPU to each other, and it was so fast that it just didn't make sense any more to think about the overhead.
So, simply go ahead and just write a simple test instead of thinking too much about a problem that may be non-existent.
Other than that, you might try like 1800 suggested with performance counters.
Oh, and I remember an application running on Windows CE 4.X, where we also have four threads with intensive switching at times, and never ran into performance issues. We also tried to implement the core threading thing without threads at all, and saw no performance improvement (the GUI just responded much slower, but everything else was the same). Maybe you can try the same, by either reducing the number of context switches or by removing threads completely (just for testing).
|
304,784
| 304,801
|
Difference between using fork/execvp and system call
|
What is the difference between using system() to execute a binary and using the combination of fork/execvp.
Is there any security/portablility/performance difference.
|
System also uses a fork/exec... combination. If you do fork/exec yourself you can execute parallel to your running process, while system is blocking (includes the wait).
Also system executes the command not direct, but via a shell (which makes problems with setuid bit) and system blocks/ignores certain signals (SIGINT, SIGCHILD, SIGQUIT).
|
304,850
| 306,193
|
Boost Spirit crash when used in DLLs
|
I am experiencing a crash while using the Boost.Spirit and Boost.Thread
libraries in my application. This only happens if I have used the Spirit
parser during the lifetime of the process from the main thread.
The crash happens at exit and appears to be related to the clean-up of
thread specific storage allocated by the Spirit parser.
It is probably crashing due to the sequence of which DLLs are
unloaded, as the thread specific memory is allocated inside a DLL
that has already been unloaded. The Boost.Thread DLL is however not unloaded untill the application itself exits.
Is there a way for me to force Spirit to clean out its thread specific
storage, e.g. in my dll-main when i get a process-detach notification?
Any solutions/hints would be appreciated.
PS!
My platform and settings:
Visual Studio 2005
BOOST_ALL_DYN_LINK
BOOST_SPIRIT_THREADSAFE
|
Well I found a workaround.
Every place I use the boost::spirit::parse call, I basically spawn a workerthread to run it, while the calling thread is blocking on a join call with the workerthread. Not ideal, but it appears to be working without any sideeffects so far.
Still interested in any alternatives as my gut feeling is that a seperate thread shouldn't really be needed.
|
304,979
| 305,061
|
Proper replacement for the missing 'finally' in C++
|
Since there is no finally in C++ you have to use the RAII design pattern instead, if you want your code to be exception safe. One way to do this is by using the destructor of a local class like this:
void foo() {
struct Finally {
~Finally() { /* cleanup code */ }
} finalizer();
// ...code that might throw an exception...
}
This is a big advantage over the straight forward solution, because you don't have to write the cleanup code 2 times:
try {
// ...code that might throw an exception...
// cleanup code (no exception)
} catch (...) {
// cleanup code (exception)
throw;
}
A big disadvantage of the local class solution is that you can't directly access local variables in your cleanup code. So it will bloat your code a lot if you need access to them regardless:
void foo() {
Task* task;
while (task = nextTask()) {
task->status = running;
struct Finally {
Task* task;
Finally(Task* task) : task(task) {}
~Finally() { task->status = idle; }
} finalizer(task);
// ...code that might throw an exception...
}
}
So my question is: Is there a solution which combines both advantages? So that you a) don't have to write duplicate code and b) can access local variables in the cleanup code, like task in the last example, but without such code bloat.
|
Instead of defining struct Finally, you could extract your cleanup code in a function of the class Task and use Loki's ScopeGuard.
ScopeGuard guard = MakeGuard(&Task::cleanup, task);
See also this DrDobb's article and this other article for more about ScopeGuards.
|
305,064
| 305,129
|
Building console apps without CRT & default headers?
|
I'm trying to build a console application without using the CRT, or any other imports than kernel32.lib in any case. I get my code to compile, but can't wrap the linker around a few problems:
unresolved external symbol @__security_check_cookie@4
unresolved external symbol "int __cdecl FreeLibrary(void *)" (?FreeLibrary@@YAHPAX@Z)
unresolved external symbol "void * __cdecl LoadLibraryW(wchar_t *)" (?LoadLibraryW@@YAPAXPA_W@Z)
unresolved external symbol "int (__cdecl*__cdecl GetProcAddress(void *,char *))(void)" (?GetProcAddress@@YAP6AHXZPAXPAD@Z)
unresolved external symbol _wmainCRTStartup
FreeLibrary, LoadLibraryW and GetProcAddress I've brought in to program explicitly, not using windows.h:
#pragma comment(lib, "kernel32.lib")
typedef int(*FARPROC)();
void* LoadLibraryW( wchar_t* lpLibFileName );
FARPROC GetProcAddress( void* hModule, char* lpProcName );
int FreeLibrary( void* hLibModule );
I suppose something is wrong with my prototypes.
However, the bigger problem are __security_check_cookie and _wmainCRTStartup, which obviously have something to do with the CRT.
So I'm wondering how I'd go about overriding the default int wmain(int argc, wchar_t* argv[]) for entrypoint, and how to get rid of whatever the security cookie is.
|
_wmainCRTStartup is the function that calls wmain()
IIRC it should be available in some .o file that you can link with, look in your lib directory.
Maybe this is useful reading too: Reduce EXE and DLL Size with LIBCTINY.LIB (and Matt Pietrek rocks :-)
|
305,077
| 305,133
|
Can I set Visual Studio 2005 to ignore assertions in a specific region of code while debugging
|
Here's the scenario. I'm debugging my own app (C/C++) which is using some library developed by another team in the company. An assertion fails when my code generates some edge case. Its a pain because the assertion is not formulated correctly so the library function is working OK but I get all these interruptions where I just have to continue (lots as its in a loop) so I can get to the stuff I'm actually interested in. I have to use the debug version of the library when debugging for other reasons. The other team wont fix this till next release (hey, it works on our machine).
Can I tell the debugger to ignore the breakpoints asserted by this section of code (i.e. can it auto-continue for me).
|
If the code is triggering breakpoints on its own (by __debugbreak or int 3), you cannot use conditional breakpoints, as the breakpoints are not know to Visual Studio at all. However, you may be able to disable any such breakpoints you are not interested in by modifying the code from the debugger. Probably not what you want, because you need to repeat this in each debugging session, however still may be better than nothing. For more information read How to disable a programmatical breakpoint / assert?.
|
305,424
| 343,840
|
AIX: Why does throwing an exception abort multithreaded code?
|
We get an abort when a C++ exception is thrown when running code compiled with -pthread.
Platform: AIX 5.3 technical level 8
Compiler: gcc 3.4.6
Linker: AIX linker 1.65.2.4
Test Code:
// exception.cpp
#include <iostream>
class MyException
{
public:
MyException(){}
virtual ~MyException(){};
};
void gTest()
{
throw MyException();
}
int main()
{
try
{
gTest();
}
catch(MyException const & ex)
{
std::cout << "exception was caught" << std::endl;
}
return 0;
}
$ g++ exception.cpp
$ ./a.out
exception was caught
$ g++ -pthread exception.cpp
$ ./a.out
terminate called after throwing an instance of 'MyException'
IOT/Abort trap (core dumped)
$ gdb a.out
GNU gdb 6.0
Copyright 2003 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "powerpc-ibm-aix5.1.0.0"...
(gdb) run
Starting program: /home/leeder/except/a.out
terminate called after throwing an instance of 'MyException'
Program received signal SIGABRT, Aborted.
Switching to Thread 1
0xd0124834 in pthread_kill () from /usr/lib/libpthreads.a(shr_xpg5.o)
(gdb) bt
#0 0xd0124834 in pthread_kill () from /usr/lib/libpthreads.a(shr_xpg5.o)
#1 0xd01242a8 in _p_raise () from /usr/lib/libpthreads.a(shr_xpg5.o)
#2 0xd0359bdc in raise () from /usr/lib/libc.a(shr.o)
#3 0xd03b7efc in abort () from /usr/lib/libc.a(shr.o)
#4 0xd0ca1800 in __gnu_cxx::__verbose_terminate_handler() () at ../../.././libstdc++-v3/libsupc++/vterminate.cc:96
#5 0xd0ca1220 in __cxxabiv1::__terminate(void (*)()) (handler=0)
at ../../.././libstdc++-v3/libsupc++/eh_terminate.cc:43
#6 0xd0ca128c in std::terminate() () at ../../.././libstdc++-v3/libsupc++/eh_terminate.cc:53
#7 0xd0ca7cfc in __cxa_throw (obj=0x200084e8, tinfo=0xffffffff, dest=Cannot access memory at address 0xffffffff
)
at ../../.././libstdc++-v3/libsupc++/eh_throw.cc:80
#8 0x100008dc in gTest() ()
#9 0x100009f0 in main ()
(gdb)
Has anyone seen anything similar?
Do you think upgrading to gcc 4 would help?
What about switching to IBM's xl compiler?
Thanks.
|
g++ 4.3.2 seems to work Ok for this problem. Also xlC v10 works.
|
305,536
| 305,731
|
What is wrong with this tiny piece of mutex code?
|
// A Mutex allows threads mutually exclusive access to a resource.
//-----------------------------------------------------------------------
class Mutex
{
private:
CRITICAL_SECTION m_mutex;
public:
Mutex() { InitializeCriticalSection(&m_mutex); }
~Mutex() { DeleteCriticalSection(&m_mutex); }
void acquire() { EnterCriticalSection(&m_mutex); }
void release() { LeaveCriticalSection(&m_mutex); }
};
Using the Entrek Codesnitch software to debug and test for any memory leaks, etc., it reports the following error:
InitializeCriticalSection Error: lpCriticalSection (0x000387d4) points to an invalid
memory location (0x00018984) Mutex::Mutex in lockmutex.h, line 29
Maybe all my sleepless nights are finally getting to me. But I don't understand what it's exactly complaining about. Any ideas?
|
I'll bet you can fake out the snitch with ::memset ( & m_mutex, 0, sizeof ( m_mutex ) ); before the call to init it.
|
305,554
| 306,018
|
C++: Do static primitives become invalid at program exit?
|
Assume I have a function like this:
MyClass &MyFunction(void)
{
static MyClass *ptr = 0;
if (ptr == 0)
ptr = new MyClass;
return MyClass;
}
The question is at program exit time, will the ptr variable ever become invalid (i.e. the contents of that ptr are cleaned up by the exiting process)? I realize that this function leaks, but it is only an example for simplicity.
The same question also applies to other primitives besides pointers as well. How about if I have a static integer, does the value of that integer always persist throughout exit or is variable due to static destruction order issues?
EDIT:
Just to clarify, I want to know what actually happens to the contents of the static pointer (or any other primitive type like an int or a float) and not to the memory it is pointing to. For instance, imagine that the ptr points to some memory address which I want to check in the destructor of some other static class. Can I rely on the fact that the contents of the ptr won't be changed (i.e. that the pointer value won't be cleaned up during the static destruction process)?
Thanks,
Joe
|
To answer your question:
'imagine that the ptr points to some memory address which I want to check in the destructor of some other static class'
The answer is yes.
You can see the value of the pointer (the address).
You can look at the content if you have not called delete on the pointer.
Static function variables behave in the same way as static class variables and global variables (aka non local static), in that there destructors will be called in reverse order of creation. Integers, floats and pointers (POD) do not have destructors so nothing happens to them until the processes is removed.
POD objects: Data can safely by referenced from the destructor of other objects (even global s).
Other static objects (i.e. those with destructors): In the general case, it is not safe to accesses these objects after main() has exited because the order of destruction is not know (it is the reverse of the order of creation, but the order of creation is complex see: Construction Order ). It can be done but you have to take explicit precautions to make sure the object is still alive.
Note: non local static:
The memory will always be there, the object will just not be valid after a destructor is called (note POD does not have a destructor).
Note: Stack:
Only valid until the scope in which they are declared is left.
After the stack is popped the memory page that it is on could potentially be dropped resulting in SEG faults if you attempt to access it.
Note: Heap:
Valid until you call delete on the pointer that allocated it.
Once a pointer is delete the value is potentially random as it may be re-used.
Potentially the page the memory was on can also be dropped. Any access to a dropped page would result in a SEG fault.
|
305,615
| 306,101
|
Timers to measure latency
|
When measuring network latency (time ack received - time msg sent) in any protocol over TCP, what timer would you recommend to use and why? What resolution does it have? What are other advantages/disadvantages?
Optional: how does it work?
Optional: what timer would you NOT use and why?
I'm looking mostly for Windows / C++ solutions, but if you'd like to comment on other systems, feel free to do so.
(Currently we use GetTickCount(), but it's not a very accurate timer.)
|
This is a copy of my answer from: C++ Timer function to provide time in nano seconds
For Linux (and BSD) you want to use clock_gettime().
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}
For windows you want to use the QueryPerformanceCounter. And here is more on QPC
Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:
QueryPerformanceCounter() and
QueryPerformanceFrequency() offer a
bit better resolution, but have
different issues. For example in
Windows XP, all AMD Athlon X2 dual
core CPUs return the PC of either of
the cores "randomly" (the PC sometimes
jumps a bit backwards), unless you
specially install AMD dual core driver
package to fix the issue. We haven't
noticed any other dual+ core CPUs
having similar issues (p4 dual, p4 ht,
core2 dual, core2 quad, phenom quad).
|
305,664
| 305,861
|
Dead-lock created by 2 SQL connections, each using transactions, different tables, foreign key constraint between the two tables
|
Environment
I'm working on a C++ application that uses SQL Native Client 9.0 to communicate with a SQL Server 2000 database.
Scenario
2 connections are opened to the DBMS
Each connection is set to use transactions
A query on Connection1 works with TableA
A query on Connection2 works with TableB
TableB has a foreign key constraint on the key_id field in TableA
I constructed the function that does the following:
begin a transaction on Connection1 & Connection2
prepare a query in TableA on Connection1
prepare a query on TableB on Connection2
begin loop over some_data
(1) insert into key_id on TableA
begin loop over some_other_data
(2) insert into TableB using same key_id as in Table A
end loop
end loop
commit on Connection1
commit on Connection2
What I encountered was that query (1) executes successfully but as soon as SQLExecute is called for query (2), the debugger goes off in never-never-land.
The Question
Am I correctly diagnosing what is happening as a dead-lock issue?
I gathered that because Connection1 is creating a key in TableA but not committing it, then Connection2 is trying to add information to TableB that, because of the foreign key constraint, must have the key present in TableA. Because of this, the SQLExecute query blocks, waiting for the transaction on TableA to complete, which it cannot do until TableB completes its write, thanks to the way the code was written.
Additional Notes
I can, and have, coded around this issue but I want to make sure my understanding of the problem is correct.
|
The foreign key constraint on TableB against TableA must check to confirm the key's existence. It will then accept or reject the TableB record.
Because the TableA record containing the key is (on a different connection) not yet commited, the Foreign Key constraint must wait - the insert will not return until the TableA record is committed or rolledback.
Because the commit on the first connection waits for the TableB insert to return... you have deadlock.
In other words, you are correct.
|
305,795
| 306,428
|
Can I make Asynchronous ODBC Calls? Any reference materials?
|
Does ODBC support asynchronous calls? If it does, then can you tell me about any reference materials?
My preferred language is C++.
|
I've wanted to know the exact same thing. An obvious workaround is to maintain a pool of threads that each perform synchronous ODBC calls and are signalled (and signal back) asynchronously.
|
305,817
| 306,858
|
C++ inserting a line into a file at a specific line number
|
I want to be able to read from an unsorted source text file (one record in each line), and insert the line/record into a destination text file by specifying the line number where it should be inserted.
Where to insert the line/record into the destination file will be determined by comparing the incoming line from the incoming file to the already ordered list in the destination file. (The destination file will start as an empty file and the data will be sorted and inserted into it one line at a time as the program iterates over the incoming file lines.)
Incoming File Example:
1 10/01/2008 line1data
2 11/01/2008 line2data
3 10/15/2008 line3data
Desired Destination File Example:
2 11/01/2008 line2data
3 10/15/2008 line3data
1 10/01/2008 line1data
I could do this by performing the sort in memory via a linked list or similar, but I want to allow this to scale to very large files. (And I am having fun trying to solve this problem as I am a C++ newbie :).)
One of the ways to do this may be to open 2 file streams with fstream (1 in and 1 out, or just 1 in/out stream), but then I run into the difficulty that it's difficult to find and search the file position because it seems to depend on absolute position from the start of the file rather than line numbers :).
I'm sure problems like this have been tackled before, and I would appreciate advice on how to proceed in a manner that is good practice.
I'm using Visual Studio 2008 Pro C++, and I'm just learning C++.
|
The basic problem is that under common OSs, files are just streams of bytes. There is no concept of lines at the filesystem level. Those semantics have to be added as an additional layer on top of the OS provided facilities. Although I have never used it, I believe that VMS has a record oriented filesystem that would make what you want to do easier. But under Linux or Windows, you can't insert into the middle of a file without rewriting the rest of the file. It is similar to memory: At the highest level, its just a sequence of bytes, and if you want something more complex, like a linked list, it has to be added on top.
|
305,849
| 305,961
|
Alternative to forward declarations when you don't want to #include
|
I usually, almost without thinking anymore, use forward declarations so that I won't have to include headers. Something along this example:
//-----------------------
// foo.h
//-----------------------
class foo
{
foo();
~foo();
};
//-----------------------
// bar.h
//-----------------------
class foo; // forward declaration
class bar
{
bar();
~bar();
foo* foo_pointer;
};
Some developers like to use this method to avoid problems with inclusion circles. I rather use it to minimize the overhead in extensive inclusion hierarchies, an important part of physical design (for larger projects in particular).
However, in some cases I really like to declare members as normal objects instead of pointers to benefit from the automatic construction/destruction mechanism. This leads to the problem that forward declarations can't be used anymore, since the compiler needs the class definition in such case, eg:
//-----------------------
// foo.h
//-----------------------
class foo
{
foo();
~foo();
};
//-----------------------
// bar.h
//-----------------------
class foo; // Not enough given the way we declare "foo_object"..
#include "foo.h" // ..instead this is required
class bar
{
bar();
~bar();
foo foo_object;
};
So, I would be happy if anyone knows an alternative language construct which can be used here so that I can declare "foo_object" as shown in the example, but without including its header.
Regards
/Robert
|
Just use a smart pointer - you can even use auto_ptr in this case.
//-----------------------
// bar.h
//-----------------------
#include <memory>
class foo; // Not enough given the way we declare "foo_object"..
class bar
{
public:
bar();
~bar();
foo &foo_object() { return *foo_ptr; }
const foo &foo_object() const { return *foo_ptr; }
private:
auto_ptr<foo> foo_ptr;
};
You get all the benefits of automatic memory management, without having to know anything about foo in bar.h. See Wrapping Pointer Data Members for Herb Sutter's recommendation.
If you really want default construction to happen automatically, try this:
#include <iostream>
using namespace std;
class Foo;
template <typename T>
class DefaultConstuctorPtr
{
T *ptr;
void operator =(const DefaultConstuctorPtr &);
DefaultConstuctorPtr(const DefaultConstuctorPtr &);
public:
DefaultConstuctorPtr() : ptr(new T()) {}
~DefaultConstuctorPtr() { delete ptr; }
T *operator *() { return ptr; }
const T *operator *() const { return ptr; }
};
class Bar
{
DefaultConstuctorPtr<Foo> foo_ptr;
public:
Bar() {} // The compiler should really need Foo() to be defined here?
};
class Foo
{
public:
Foo () { cout << "Constructing foo"; }
};
int main()
{
Bar bar;
}
|
306,316
| 306,332
|
Determine if two rectangles overlap each other?
|
I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to the x and the y axis, that is all of their edges will have slopes of 0 or infinity.
I've tried to implement what is mentioned in this question but I am not having very much luck.
My current implementation does the following:
// Gets all the vertices for Rectangle 1 and stores them in an array -> arrRect1
// point 1 x: arrRect1[0], point 1 y: arrRect1[1] and so on...
// Gets all the vertices for Rectangle 2 and stores them in an array -> arrRect2
// rotated edge of point a, rect 1
int rot_x, rot_y;
rot_x = -arrRect1[3];
rot_y = arrRect1[2];
// point on rotated edge
int pnt_x, pnt_y;
pnt_x = arrRect1[2];
pnt_y = arrRect1[3];
// test point, a from rect 2
int tst_x, tst_y;
tst_x = arrRect2[0];
tst_y = arrRect2[1];
int value;
value = (rot_x * (tst_x - pnt_x)) + (rot_y * (tst_y - pnt_y));
cout << "Value: " << value;
However I'm not quite sure if (a) I've implemented the algorithm I linked to correctly, or if I did exactly how to interpret this?
Any suggestions?
|
if (RectA.Left < RectB.Right && RectA.Right > RectB.Left &&
RectA.Top > RectB.Bottom && RectA.Bottom < RectB.Top )
or, using Cartesian coordinates
(With X1 being left coord, X2 being right coord, increasing from left to right and Y1 being Top coord, and Y2 being Bottom coord, increasing from bottom to top -- if this is not how your coordinate system [e.g. most computers have the Y direction reversed], swap the comparisons below) ...
if (RectA.X1 < RectB.X2 && RectA.X2 > RectB.X1 &&
RectA.Y1 > RectB.Y2 && RectA.Y2 < RectB.Y1)
Say you have Rect A, and Rect B.
Proof is by contradiction. Any one of four conditions guarantees that no overlap can exist:
Cond1. If A's left edge is to the right of the B's right edge,
- then A is Totally to right Of B
Cond2. If A's right edge is to the left of the B's left edge,
- then A is Totally to left Of B
Cond3. If A's top edge is below B's bottom edge,
- then A is Totally below B
Cond4. If A's bottom edge is above B's top edge,
- then A is Totally above B
So condition for Non-Overlap is
NON-Overlap => Cond1 Or Cond2 Or Cond3 Or Cond4
Therefore, a sufficient condition for Overlap is the opposite.
Overlap => NOT (Cond1 Or Cond2 Or Cond3 Or Cond4)
De Morgan's law says
Not (A or B or C or D) is the same as Not A And Not B And Not C And Not D
so using De Morgan, we have
Not Cond1 And Not Cond2 And Not Cond3 And Not Cond4
This is equivalent to:
A's Left Edge to left of B's right edge, [RectA.Left < RectB.Right], and
A's right edge to right of B's left edge, [RectA.Right > RectB.Left], and
A's top above B's bottom, [RectA.Top > RectB.Bottom], and
A's bottom below B's Top [RectA.Bottom < RectB.Top]
Note 1: It is fairly obvious this same principle can be extended to any number of dimensions.
Note 2: It should also be fairly obvious to count overlaps of just one pixel, change the < and/or the > on that boundary to a <= or a >=.
Note 3: This answer, when utilizing Cartesian coordinates (X, Y) is based on standard algebraic Cartesian coordinates (x increases left to right, and Y increases bottom to top). Obviously, where a computer system might mechanize screen coordinates differently, (e.g., increasing Y from top to bottom, or X From right to left), the syntax will need to be adjusted accordingly/
|
306,533
| 306,542
|
How do I get a list of files in a directory in C++?
|
How do you get a list of files within a directory so each can be processed?
|
But boost::filesystem can do that: http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp
|
306,559
| 306,691
|
Passing boost::any to results of boost::bind
|
I'm trying to figure out how to write this function:
template <typename Bound>
Bound::result_type callFromAnyList(Bound b, list<any> p)
{
}
Then, if I had some function:
double myFunc(string s, int i)
{
return -3.0;
}
I could call it by doing something like this:
list<any> p;
p.push_back((string)"Hello");
p.push_back(7);
double result = callFromAnyList(bind(myFunc, _1, _2), p);
Is it possible to write something like my callFromAnyList function? Can you inspect the result type and the parameter types from the type returned from bind? And then call any_cast<P1>(*p.begin()), etc? I've tried to understand the bind code, but it's a little hard to follow, and it doesn't appear as though they wrote it with inspection in mind.
|
As you updated your concerns in the comment sections, here the answer. Just getting the return type of a function is possible:
template<typename>
struct return_of;
template<typename R>
struct return_of<R(*)()> {
typedef R type;
};
template<typename R, typename P1>
struct return_of<R(*)(P1)> {
typedef R type;
typedef P1 parameter_1;
};
void foo(int);
template<typename Func>
typename return_of<Func>::parameter_1 bar(Func f) {
return 42;
}
// call: bar(foo);
I guess you see what this comes down to :) You can use boost function types which already has solved it: http://www.boost.org/doc/libs/1_37_0/libs/function_types/doc/html/index.html
|
307,082
| 307,360
|
Cleaning up an STL list/vector of pointers
|
What is the shortest chunk of C++ you can come up with to safely clean up a std::vector or std::list of pointers? (assuming you have to call delete on the pointers?)
list<Foo*> foo_list;
I'd rather not use Boost or wrap my pointers with smart pointers.
|
Since we are throwing down the gauntlet here... "Shortest chunk of C++"
static bool deleteAll( Foo * theElement ) { delete theElement; return true; }
foo_list . remove_if ( deleteAll );
I think we can trust the folks who came up with STL to have efficient algorithms. Why reinvent the wheel?
|
307,343
| 307,408
|
Forward declare a standard container?
|
Is it possible to forward declare an standard container in a header file? For example, take the following code:
#include <vector>
class Foo
{
private:
std::vector<int> container_;
...
};
I want to be able to do something like this:
namespace std
{
template <typename T> class vector;
}
class Foo
{
private:
std::vector<int> container_;
...
};
Can this be done?
|
Declaring vector in the std namespace is undefined behavior. So, your code might work, but it also might not, and the compiler is under no obligation to tell you when your attempt won't work. That's a gamble, and I don't know that avoiding the inclusion of a standard C++ header is worth that.
See the following comp.std.c++.moderated discussion:
forward declaring std::vector. Works, but is it legal and standard compliant?
|
307,352
| 307,427
|
g++ undefined reference to typeinfo
|
I just ran across the following error (and found the solution online, but it's not present in Stack Overflow):
(.gnu.linkonce.[stuff]): undefined
reference to [method] [object
file]:(.gnu.linkonce.[stuff]):
undefined reference to `typeinfo for
[classname]'
Why might one get one of these "undefined reference to typeinfo" linker errors?
(Bonus points if you can explain what's going on behind the scenes.)
|
One possible reason is because you are declaring a virtual function without defining it.
When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).
An example of defining the virtual function is:
virtual void fn() { /* insert code here */ }
In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.
The line
virtual void fn();
declares fn() without defining it and will cause the error message you asked about.
It's very similar to the code:
extern int i;
int *pi = &i;
which states that the integer i is declared in another compilation unit which must be resolved at link time (otherwise pi can't be set to it's address).
|
307,369
| 307,415
|
What is the strtok_s equivalent in VC7?
|
The strtok_s function exists in vc8 but not in vc7. So what's a function (or code) that does the equivalent of strtok_s in vc7?
|
Take a look at this MSDN page.
As far as I can tell, the security enhancements a) Make strtok() reentrant (and thread-safe) by having it take a "context" parameter and b) Make it safe to use with NULL pointers. (The actual behaviors in the case of NULL parameters are listed in a table on the page I've linked.)
As for a VC7 alternative, you'll have to write (or import) one yourself. The NULL-safety is easy to do externally, you'll just have to be careful not to pass NULL strings where none are expected; but as far as reentrancy goes, there's no way for strtok() to handle that.
Take a look at this and this question. I believe POSIX also supplies a reentrant version of strtok() called strtok_r(); you can search for it. It would also be a good (and short) exercise to write an implementation yourself. Shouldn't take more than ~10 lines of code.
|
307,478
| 308,270
|
Automated Dead code detection in native C++ application on Windows?
|
Background
I have an application written in native C++ over the course of several years that is around 60 KLOC. There are many many functions and classes that are dead (probably 10-15% like the similar Unix based question below asked). We recently began doing unit testing on all new code and applying it to modified code whenever possible. However, I would make a SWAG that we have less than 5% test coverage at the present moment.
Assumptions/Constraints
The method and/or tools must support:
Native (i.e. unmanaged) C++
Windows XP
Visual Studio 2005
Must not require user supplied test cases for coverage. (e.g. can't depend on unit tests to generate code coverage)
If the methods support more than these requirements, then great.
NOTE: We currently use the Professional edition of Visual Studio 2005, not the Team System. Therefore, using Team System might be a valid suggestion (I don't know, I've never used it) however I'm hoping it is not the only solution.
Why using unit tests for code coverage is problematic
I believe that it is impossible for a generic tool to find all the dead (e.g. unreachable code) in any arbitrary application with zero false positives (I think this would be equivalent to the Halting problem). However, I also believe it is possible for a generic tool to find many types of dead code that are highly probable to in fact be dead, like classes or functions which are never reference in the code by anything else.
By using unit tests to provide this coverage, you no longer using a generic algorithm and are thus increasing both the percentage of dead code you can detect and the probability that any hits are not false positives. Conversely, using unit tests could result in false negatives since the unit tests themselves might be the only thing exercising a given piece of code. Ideally, I would have regression testing that exercises all externally available methods, APIs, user controls, etc. which would serve as a baseline measurement of code coverage analysis to rule out certain methods from being false positives. Sadly however, I do not have this automated testing at the present time.
Since I have such a large code base with such a low test case coverage percentage however, I'm looking for something that could help without requiring huge amounts of time invested in writing test cases.
Question
How do you go about detecting dead code in an automated or semi-automated fashion in a native C++ application on the Windows platform with the Visual Studio 2005 development environment?
See Also
Dead code detection in legacy C/C++ project
I want tell the VC++ Compiler to compile all code. Can it be done?
|
Ask the linker to remove unreferenced objects (/OPT:REF). If you use function-level linking, and verbose linker output, the linker output will list every function it can prove is unused. This list may be far from complete, but you already have the tools needed.
|
307,524
| 307,537
|
Can you have protected nested classes in C++?
|
I have a class that only really ever needed by classes in a certain class hierarchy. I wanted to know if it is possible to nest the class in the highest class's protected section and have all the other classes automatically inherit it?
|
"Inherit" is the wrong word to use since it has a very specific definition in C++ which you don't mean, but yes you can do that. This is legal:
class A {
protected:
class Nested { };
};
class B : public A {
private:
Nested n;
};
And code that is not in A or something that derives from A cannot access or instantiate A::Nested.
|
307,596
| 307,607
|
Time difference in C++
|
Does anyone know how to calculate time difference in C++ in milliseconds?
I used difftime but it doesn't have enough precision for what I'm trying to measure.
|
You have to use one of the more specific time structures, either timeval (microsecond-resolution) or timespec (nanosecond-resolution), but you can do it manually fairly easily:
#include <time.h>
int diff_ms(timeval t1, timeval t2)
{
return (((t1.tv_sec - t2.tv_sec) * 1000000) +
(t1.tv_usec - t2.tv_usec))/1000;
}
This obviously has some problems with integer overflow if the difference in times is really large (or if you have 16-bit ints), but that's probably not a common case.
|
307,765
| 307,793
|
How do I check if an object's type is a particular subclass in C++?
|
I was thinking along the lines of using typeid() but I don't know how to ask if that type is a subclass of another class (which, by the way, is abstract)
|
You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.
I am assuming you have a situation like this:
class Base;
class A : public Base {...};
class B : public Base {...};
void foo(Base *p)
{
if(/* p is A */) /* do X */
else /* do Y */
}
If this is what you have, then try to do something like this:
class Base
{
virtual void bar() = 0;
};
class A : public Base
{
void bar() {/* do X */}
};
class B : public Base
{
void bar() {/* do Y */}
};
void foo(Base *p)
{
p->bar();
}
Edit: Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates Liskov substitution principle. Uncle Bob calls this an "anathema to Object Oriented Design".
|
307,900
| 308,004
|
Complex builds in Visual Studio
|
I have a few things that I cannot find a good way to perform in Visual Studio:
Pre-build step invokes a code generator that generates some source files which are later compiled. This can be solved to a limited extent by adding blank files to the project (which are later replaced with real generated files), but it does not work if I don't know names and/or the number of auto-generated source files. I can easily solve it in GNU make using $(wildcard generated/*.c). How can I do something similar with Visual Studio?
Can I prevent pre-build/post-build event running if the files do not need to be modified ("make" behaviour)? The current workaround is to write a wrapper script that will check timestamps for me, which works, but is a bit clunky.
What is a good way to locate external libraries and headers installed outside of VS? In *nix case, they would normally be installed in the system paths, or located with autoconf. I suppose I can specify paths with user-defined macros in project settings, but where is a good place to put these macros so they can be easily found and adjusted?
Just to be clear, I am aware that better Windows build systems exist (CMake, SCons), but they usually generate VS project files themselves, and I need to integrate this project into existing VS build system, so it is desirable that I have just plain VS project files, not generated ones.
|
If you need make behavior and are used to it, you can create visual studio makefile projects and include them in your project.
If you want less clunky, you can write visual studio macros and custom build events and tie them to specific build callbacks / hooks.
You can try something like workspacewhiz which will let you setup environment variables for your project, in a file format that can be checked in. Then users can alter them locally.
|
307,928
| 307,981
|
What is the difference between CString in vc6 and vc7?
|
What is the difference between CString in vc6 and vc7?
|
CString was removed from MFC in VC7 so that it could be used in both MFC and ATL projects. The architecture was completely changed:
In VC6, CString had no base class. In VC7, the base class is CStringT<TCHAR> which derives from CSimpleStringT<TCHAR>.
In VC7, you also get CStringA and CStringW for explicit char and wchar_t strings.
I'm not aware of any behavior differences between them, but the documentation is much easier to use in VC6. The methods are scattered between the base classes in VC7.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.