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 tac... | 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 complete... |
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 ob... | 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... |
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, w... | 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::bi... |
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 h... | 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 of... |
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 V... | 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 compiler... | 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 Sma... |
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 IFo... | 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 ... |
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 w... | 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 y... |
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 leng... | 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 a... |
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... | 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();
lon... |
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:
[[d... |
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 wh... | 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,... |
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 ... | 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 ... | 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 t... |
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 thin... |
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:
MyCla... |
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 th... | 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 ... |
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 ex... | 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 wi... |
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... | 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 ... |
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... | 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... | 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... |
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 Stu... | 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 {... |
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::li... | 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... | 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 st... |
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... | 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 c... |
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... | 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 Custome... |
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 in... | 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 Exec... |
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,... |
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 imple... | 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... |
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, ... | 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:
i... |
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 ... | 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 X... |
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 s... | 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 r... |
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... |
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... | 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 ... |
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 spe... |
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... | 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_vec... |
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 /head... | 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 att... | 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 s... |
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 ide... | 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 ... |
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... | 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 clo... | 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::s... | 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 ... |
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 --... | 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 hav... |
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... | 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 y... |
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... | 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 ... |
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;
// pr... | 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... |
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];
dou... |
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 thi... | 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, bu... |
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 ... | 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... | 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/op... |
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... | 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 ... |
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 i... | 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 ... |
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... |
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 ... | 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 feeli... |
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... | 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... | _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... | 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 ... |
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 gTe... | 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); }
voi... | 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 thi... | 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 beh... |
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 / ... | 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 win... |
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 ke... | 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 Table... |
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 i... | 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... |
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; // forwa... | 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... |
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 ment... | 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... |
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_... | 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;
... |
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
{
privat... | 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... |
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 t... | 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 exa... |
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... |
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 cod... | 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 ... |
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_use... |
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 : p... |
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... |
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 yo... |
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 wch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.