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 |
|---|---|---|---|---|
555,774 | 555,784 | Reconciling classes, inheritance, and C callbacks | In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I ... | You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class Libr... |
556,064 | 556,092 | STL-like vector with arbitrary index range | What I want is something similar to STL vector when it comes to access complexity, reallocation on resize, etc. I want it to support arbitrary index range, for example there could be elements indexed from -2 to +7 or from +5 to +10. I want to be able to push_front efficiently. Also I want two-way resize...
I know I cou... | Deque is very much like a vector in that it supports random access and efficient insertion at the end and it also supports efficient insertion at the beginning.
Map supports access based on arbitrary keys, you can have any range you want, or even a sparsely populated array. Iteration over the collection is slow.
Unorde... |
556,255 | 556,366 | How to throw good exceptions? | I heard you should never throw a string because there is a lack of information and you'll catch exceptions you dont expect to catch. What are good practice for throwing exceptions? do you inherit a base exception class? Do you have many exceptions or few? do you do MyExceptionClass& or const MyExceptionClass& ? etc. A... | In my opinion, a function should throw an exception if it can't keep its "promise", if it has to break its "contract". The function's signature (name and parameters) determine its contract.
Given these two member functions:
const Apple* FindApple(const wchar_t* name) const;
const Apple& GetApple(const wchar_t* name) co... |
556,277 | 556,340 | Trim / remove a tab ( "\t" ) from a string | Can anyone suggest a way of stripping tab characters ( "\t"s ) from a string? CString or std::string.
So that "1E10 " for example becomes "1E10".
| hackingwords' answer gets you halfway there. But std::remove() from <algorithm> doesn't actually make the string any shorter -- it just returns an iterator saying "the new sequence would end here." You need to call my_string().erase() to do that:
#include <string>
#include <algorithm> // For std::remove()
my_str.... |
556,309 | 566,047 | How to embed lua in c++ via SWIG | Currently I have a set of SWIG wrappers for my classes and it all builds. I can create a lua virtual machine and load my wrappers, but at that point I'm flummoxed. Googling tells me how to shove put c++ in lua in swig, but not how to put lua in c++.
Really all I want to do is manage to instantiate a lua object and pass... | Take a look at the Programming in Lua book, it has a section on the Lua C API.
For calling Lua functions use lua_pcall, which is equivalent to lua_call (that has a short example) except it will catch Lua runtime errors.
You must have already loaded and run the script once (using eg. luaL_dofile) since the first step is... |
556,525 | 556,596 | Raw socket implementation in windows? | I need to create TCP/IP headers manually for my application. For that i used Raw socket. My system os is win xp (SP3).
My code compiles fine :) but it throws a run time error:
Initialising Winsock...Initialised successfully. Creating Raw TCP Socket...Raw TCP Socket Created successfully. Setting the socket in RAW mod... | I suggest using WinPcap for this purpose. Even when you figure out how to do this properly with the win32 API it is going to be horribly slow.
I've used WinPcap successfully to inject packets to a Gigabit ethernet port as fast as the hardware can handle.
|
556,655 | 556,716 | Throwing/catching exceptions from C'tor of a static object in C++ | I have a case in which I have to read an input file in the C'tor, but sometimes this file doesn't exist.
This object is usually held statically, so its C'tor is called while loading the dll.
I can't catch the exception I throw if the file doesn't exist because it's too early, and my executable crashes in an ugly way.
I... | I assume the static object has the file scope (it is outside any function/class definition). You may consider moving it to an accessor function and accessing it only via that function, like this:
class Object;
Object& getObject()
{
static Object object;
return object;
}
The static instance of Object will be in... |
556,807 | 556,846 | Does a Java to C++ converter/tool exist? | I always asked myself if it would be possible to make a Java to C++ converter.
Maybe a tool that converts the Java syntax to the C++ syntax?
I am aware that the languages differ, but simple things like loops where the semantics match 1 to 1.
Is there such a tool? Or is it possible to make one?
| It's possible to do anything given enough time, money and resources. Is it practical? Beyond trivial examples not really. Or rather it depends on what constitutes an acceptable error rate.
The real problem is that the idioms are different in Java to C++. Java to C# for example would actually be far easier (because ... |
556,838 | 557,408 | map complex find operation | I want to do the following:
Define a map between a string and any kind of object (may be a list, integer - anything).
The keys to the map can be as follow (the values are, again, not important):
"AAA/123" ==> 1
"AAA/" ==> 2
"BBB/" ==> 3
"CCC/*" ==> 4
"CCC/123" ==> 5
Now, the trick is I want to find the right values giv... | Here's a variant of litb answer (which was somehow deleted from the answers list) which might work given the '*' is removed:
template<typename Map> typename Map::const_iterator
find_prefix(Map const& map, typename Map::key_type const& key)
{
typename Map::const_iterator it = map.upper_bound(key);
while (it !=... |
556,892 | 561,307 | How can I launch the on-screen keyboard from my application on Vista and Windows 7 | I have a problem, I have an application which has a toolbar icon to launch the system onscreen keyboard. This all works fine with the exception of Windows Vista and Windows 7 beta. The UAC appears to be getting in the way and preventing the osk.exe from running.
I have read that because it is used on the logon screen... | OK, it was more about specifics it turned out.
I was using Qt's QProcess::startDetached which I believe uses the CreateProcess function call on windows.
I changed the code to use the ShellExecute() function call and it works like a charm.
Strangely...
|
556,997 | 557,047 | How can I create a guid in MFC | I need to be able to create guids on the fly. Is there a way to do that in MFC? I see how to do it in .net, but we haven't gone there yet. If not, do you have pointers to some code I can use?
| GUID guid;
HRESULT hr = CoCreateGuid(&guid);
// Convert the GUID to a string
_TUCHAR * guidStr;
UuidToString(&guid, &guidStr);
The application is responsible for calling RpcStringFree to deallocate the memory allocated for the string returned in the StringUuid parameter.
|
557,081 | 557,774 | How do I get the HMODULE for the currently executing code? | I have a static library that may get linked into either a .exe or a .dll. At runtime I want one of my library functions to get the HMODULE for whatever thing the static library code has been linked into.
I currently use the following trick (inspired from this forum):
const HMODULE GetCurrentModule()
{
MEMORY_BASIC... | HMODULE GetCurrentModule()
{ // NB: XP+ solution!
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)GetCurrentModule,
&hModule);
return hModule;
}
|
557,170 | 557,422 | Bit Operation For Finding String Difference | The following string of mine tried to find difference between two strings.
But it's horribly slow as it iterate the length of string:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int hd(string s1, string s2) {
// hd stands for "Hamming Distance"
int dif = 0;
for (unsigned ... | Fun with the STL:
#include <numeric> //inner_product
#include <functional> //plus, equal_to, not2
#include <string>
#include <stdexcept>
unsigned int
hd(const std::string& s1, const std::string& s2)
{
// TODO: What should we do if s1.size() != s2.size()?
if (s1.size() != s2.size()){
throw std::inv... |
557,317 | 557,331 | Is __declspec(dllexport) needed in cpp files | Probably a simple question but I only have Linux to test this code on where __declspec(dllexport) is not needed. In the current code __declspec(dllexport) is in front of all files in the .h file but just in front of like 50% of the functions in the cpp file so I am wondering if they are really needed in the cpp file at... | No, its only needed in the header.
Here's a link with more info.
Expanding on what Vinay was saying, I've often seen a macro defined
#if defined(MODULENAME_IMPORT)
#define EXPORTED __declspec(dllimport)
#elif defined(MODULENAME_EXPORT)
#define EXPORTED __declspec(dllexport)
#endif
Then in your header you do
void EXPOR... |
557,466 | 557,475 | How to create an auto startup c++ program | I am creating a program in c++, which I want to be able to have the option to have users let it auto start in windows. So when a user starts his computer, windows will auto start this program. I have read stuff about modifying the registry or putting it in the startup folder, but what would be the best "clean" way to d... | Startup folder is clean enough.
Gives the user the possibility to remove it if needed.
|
557,553 | 557,569 | C++ bound method queue (task manager/scheduler?) | Is there a method/pattern/library to do something like that (in pseudo-code):
task_queue.push_back(ObjectType object1, method1);
task_queue.push_back(OtherObjectType object2, method2);
so that I could do the something like:
for(int i=0; i<task_queue.size(); i++) {
task_queue[i].object -> method();
}
so that it wo... | Yes you would want to combine boost::bind and boost::functions its very powerful stuff.
This version now compiles, thanks to Slava!
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <vector>
class CClass1
{
public:
void AMethod(int i, float f) { std::cout << "CClass1::AMethod(" <... |
557,800 | 557,869 | Find the unix platform name | I want to be able to determine the output folder based on the platform name: AS3, AS4, AS5, SUN.
I couldn't figure out how to extract the platform name from the system. I experimented with:
uname -a
file /bin/bash
Thanks
Solution
./lsb_release -a
Kudos to Paul Dixon
| Some linux systems will have support for lsb_release
|
558,223 | 558,259 | va_copy -- porting to visual C++? | A previous question showed a nice way of printing to a string. The answer involved va_copy:
std::string format (const char *fmt, ...);
{
va_list ap;
va_start (ap, fmt);
std::string buf = vformat (fmt, ap);
va_end (ap);
return buf;
}
std::string vformat (const char *fmt, va_list ap)
{
// Allocate a b... | You should be able to get away with just doing a regular assignment:
va_list apcopy = ap;
It's technically non-portable and undefined behavior, but it will work with most compilers and architectures. In the x86 calling convention, va_lists are just pointers into the stack and are safe to copy.
|
558,366 | 558,408 | Tracing write access to class instance/memory range in gdb | I am trying to debug a small operating system I have written in an university course in C++. At runtime somewhere one of my objects is getting corrupted. It seems like this happens due to accidentally writing to the wrong memory address. As I am unable to find the place where this happens from pure looking at the code,... | You can put a watchpoint:
watch x
This will break when x is modified. x can be any type of variable. If you have:
class A;
A x;
Then gdb will break whenever x is modified.
You can actually put a watchpoint on any expression, and gdb will break when the expression changes. Be careful with this, though, because if t... |
558,474 | 558,480 | What makes more sense - char* string or char *string? | I'm learning C++ at the moment, and I'm coming across a lot of null-terminated strings. This has got me thinking, what makes more sense when declaring pointers:
char* string
or
char *string
? To me, the char* format makes more sense, because the type of "string" is a pointer to a char, rather than a char. However, I ... | In the following declaration:
char* string1, string2;
string1 is a character pointer, but string2 is a single character only. For this reason, the declaration is usually formatted like:
char *string1, string2;
which makes it slightly clearer that the * applies to string1 but not string2. Good practice is to avoid dec... |
558,848 | 558,900 | Can I force cache coherency on a multicore x86 CPU? | The other week, I wrote a little thread class and a one-way message pipe to allow communication between threads (two pipes per thread, obviously, for bidirectional communication). Everything worked fine on my Athlon 64 X2, but I was wondering if I'd run into any problems if both threads were looking at the same variab... | volatile only forces your code to re-read the value, it cannot control where the value is read from. If the value was recently read by your code then it will probably be in cache, in which case volatile will force it to be re-read from cache, NOT from memory.
There are not a lot of cache coherency instructions in x86.... |
559,025 | 559,118 | Compiler-Programming: What are the most fundamental ingredients? | I am interested in writing a very minimalistic compiler.
I want to write a small piece of software (in C/C++) that fulfills the following criteria:
output in ELF format (*nix)
input is a single textfile
C-like grammar and syntax
no linker
no preprocessor
very small (max. 1-2 KLOC)
Language features:
native data type... | Firstly, you need to decide whether you are going to make a compiler or an interpreter. A compiler translates your code into something that can be run either directly on hardware, in an interpreter, or get compiled into another language which then is interpreted in some way. Both types of languages are turing complete ... |
559,179 | 559,191 | linking to boost regex in gcc | i am trying to compile my program which uses regex on linux. I built the boost library in the
libs/regex/build
by typing
make -fgcc.mak
which created a directory gcc which contains the following four files
boost_regex-gcc-1_35
boost_regex-gcc-d-1_35
libboost_regex-gcc-1_35.a
libboost_regex-gcc-d-1_35.a
Now I w... | Either add libboost_regex-gcc-1_35.a to your list of object files in your link step or add -static -lboost_regex-gcc-1_35 to the same. Also be sure that you have an -I switch pointing to your boost includes directory in your compile step. If the libraries are outside the typical search path (/usr/lib on *nix), add that... |
559,274 | 559,285 | Any program or trick to find the definition of a variable? | Many times when I am watching others code I just want to find where and how a variable is defined. Normally what I do now is look for the type of the variable until I find the definition, that is very time consuming. And I guess that there are some tools that can help me in this rutinary situation. Any suggestion in so... | Edit: OK, you say you're using C++. I'm editing my response. I would use the C preprocessor and then grep for the variable. It will appear in the first place.
cpp -I...(preprocessor options here) file.cpp | grep variable
The C preprocessor will join all the includes that the program uses, and the definition has to be ... |
559,294 | 559,302 | Direct 3D affecting data type double | I recently added some DirectX code to my program, and now my double data type variables only have the range/resolution of a float (.. or atleast less range/resolution than they used to). If I remove the direct3D initialization - "Direct3DCreate9(D3D_SDK_VERSION)" - the problem goes away. Any insight? Thanks.
| Direct3D will modify the FPU state to force single precision mode.
If you want to preserve double-precision mode, use D3DCREATE_FPU_PRESERVE when you create the D3D device. That will have an effect on the performance of D3D though:
http://msdn.microsoft.com/en-us/library/bb172527(VS.85).aspx
|
559,440 | 559,459 | getline() in C++ - _GNU_SOURCE not needed? | Firstly, I'm pretty new to C++. I believe that getline() isn't a standard C function, so #define _GNU_SOURCE is required to use it. I'm now using C++ and g++ tells me that _GNU_SOURCE is already defined:
$ g++ -Wall -Werror parser.cpp
parser.cpp:1:1: error: "_GNU_SOURCE" redefined
<command-line>: error: this is the loc... | I think g++, from version 3, automagically defines _GNU_SOURCE. This is supported by your third line in the error stating that the first definition was done on the command line (with nary a -D_GNU_SOURCE in sight):
<command-line>: error: this is the location of the previous definition
If you don't want it, #undef it ... |
559,522 | 559,595 | Separate header files for concrete classes - C++ | Background
I have an abstract class, something like
class IConverter{
public:
virtual void DoConvertion() = 0;
};
There will be many concrete classes which just implements DoConvertion method.
class TextConverter : public IConverter{
public:
virtual void DoConvertion(){
// my code goes here
... | Something you might consider, depending on the rest of your design, is a factory, where your abstract class has a static method (or multiple static methods, depending on how you implement it) that constructs the appropriate subclass and returns it as an IConverter*. With this, you can expose only the abstract definiti... |
559,762 | 559,913 | How parse a string in C++ | I want to parse the strings, so that to check whether they have specified syntax or not.
Example:
Str = Z344-R565l t
Here my requirement is after Z there should be a number and after that a - and after that R should be there followed by a number, followed by l, followed by a space and then finally t.
If any thing oth... | Use boost::regex
#include <string>
#include <boost/regex.hpp>
bool isMatch(std::string input){
boost::regex r("Z[0-9]*-R[0-9]*l t");
return boost::regex_search(input, r);
}
The other thing that you could do is supply a list of regex expressions in a file, one expression per line. Create a vector of boost::re... |
559,918 | 560,034 | C++0x: Range overloads for standard algorithms? | std::sort(range(c));
as opposed to
std::sort(c.begin(), c.end();
Do you expect the next standard to provide range overloads for standard algorithms?
Boost's range iterators are something similar, and Bjarne Stroustrup's iseq()s mentioned in TC++PL3e are also the same idea. I have looked at the latest draft I could f... | The History page provides a partial answer.
There has to be a compelling need to add overloads to the std namespace. Note, this is a Library Issue. You can search the archives to find if anyone has previously raised a request to add these to the library. If there isn't any you can submit a defect report. The current la... |
560,089 | 560,098 | Unix Command For Benchmarking Code Running K times | Suppose I have a code executed in Unix this way:
$ ./mycode
My question is is there a way I can time the running time of my code
executed K times. The value of K = 1000 for example.
I am aware of Unix "time" command, but that only executed 1 instance.
| try
$ time ( your commands )
write a loop to go in the parens to repeat your command as needed.
Update
Okay, we can solve the command line too long issue. This is bash syntax, if you're using another shell you may have to use expr(1).
$ time (
> while ((n++ < 100)); do echo "n = $n"; done
> )
real 0m0.001s
user ... |
560,091 | 560,112 | Publish/Subscribe and Smart pointer | I would like to implement a simple Publish/Subscribe pattern where:
A single publisher publishes a token (a pointer to an object) to its subscribers. Publisher and subscribers are all independent threads. I plan to add thread-safe queue to each of the subscriber such that Publisher can keep distributing the tokens to t... | If I assume your design is viable (it smells funny with zero context, but may well be correct), boost::shared_ptr might be the way to go.
http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm
Edit: switch to ::shared_ptr from ::weak_ptr, because I am an idiot...
|
560,322 | 560,516 | How else to achieve "templated function pointers"? | Is it possible to establish a set of templated function pointers, without the hassle of doing so manually? Here's an example to illustrate what the heck I'm talking about.
Let's say I have a frequently-called function "write" of which I have two implementations (write0 and write1) that I'd like to be able to switch be... | If you want to switch logging functions back and forth while the program runs, I think you have to manually set the function pointer for each type.
If it's enough to just choose the logging function at startup, it can be done in a fully generic way without even knowing for which types the function will be called later:... |
560,344 | 560,417 | How does one disassemble Pro*C/C++ programs? | Is there a way to disassemble Pro*C/C++ executable files?
| In general there should be disassemblers available for executables, regardless how they have been created (gcc, proC, handwritten, etc.) but decompiling an optimized binary most probably leads to unreadable or source.
Also, Pro C/C++ is not directly a compiler but outputs C/C++ code which then in turn is compiled by a ... |
560,845 | 560,903 | What are the often misunderstood concepts in C++? | What are the often misunderstood concepts in c++?
| C++ is not C with classes!
And there is no language called C/C++. Everything goes downhill from there.
|
561,115 | 561,176 | Problems writing a copy constructor for a smart pointer | The code I'm working with has its own smart pointer implementation which does simple reference counting. Yes, we shouldn't have our own implementation. Yes, we should be using one from boost or some such. Bear with me.
I found I wanted to write code like this:
...
CountedPointer<Base> base;
...
CountedPointer<Derived> ... | Can't you make them friends? Like:
template<typename T>
class CountedPointer {
// ...
template<U>
CountedPointer(const CountedPointer<U> &other);
template<typename U> friend class CountedPointer;
};
|
561,339 | 561,352 | A question about sizeof and class member function | class B
{
public:
int a;
void fn();
}
If I create an object of B, using
B* pb = new B;
Where is the memory of fn() locate?
Is there a pointer in object that pointing at the memory loaction of fn()?
If yes, why sizeof(B) returns the value as if there is no pointer in object at all?
|
Where is the memory of fn() locate?
Since it's a normal function, somewhere in the code section of your program. This location is the same for all instances of the class. In fact, it has got nothing to do with the instantiation of B via pb.
Is there a pointer in object that pointing at the memory loaction of fn()?
... |
561,588 | 561,609 | What is more efficient, i++ or ++i? | Exact Duplicate: Is there a performance difference between i++ and ++i in C++?
Exact Duplicate: Difference between i++ and ++i in a loop?
What is more efficient, i++ or ++i?
I have only used this in Java and C/C++, but I am really asking for all languages that this is implemented in.
In college I had a professor show... | i++ :
create a temporary copy of i
increment i
return the temporary copy
++i :
increment i
return i
With optimizations on, it is quite possible that the resulting assembly is identical, however ++i is more efficient.
edit : keep in mind that in C++, i may be whatever object that support the prefix and postfix ++ op... |
561,730 | 561,781 | partial template specialization for dynamic dispatch | I am attempting to write a dynamic dispatcher for a function that's templated on integer values (not on types). While I could either write a code generator or use a big macro chain to create the dispatcher source, it seems that a templated solution would be more elegant.
I've stripped down my dispatcher to a simple fo... | You're simply not calling the f() function in your recursive call, you're trying to "call the object":
You write:
TestDispatcher2D<...> t;
return t(m,n);
But you want:
TestDispatcher2D<...> t;
return t.f(m,n);
|
561,839 | 561,847 | What is the difference between 'WCHAR' and 'wchar_t'? | Is there any practical difference between WCHAR and wchar_t?
| Well, one practical difference would be that WCHAR doesn't exist on my platform. For Windows only (and with no intention of ever porting the program to another platform) and with the necessary headers included, it's the same (since WCHAR is just a typedef).
|
561,949 | 562,021 | What are some C++ Standard Library usage best practices? | I'm learning C++ and the book I'm reading (The C++ Programming Language) says to not reinvent the wheel, to rely on the standard libraries. In C, I often end up creating a linked list, and link list iteration over and over again (maybe I'm doing that wrong not sure), so the ideas of containers available in C++, and str... | There is a companion book to the Effective C++ series, which is called "Effective STL". It's a good starting point for learning about best practises using the Standard C++ library (neé STL).
|
561,997 | 562,465 | Determining exception type after the exception is caught? | Is there a way to determine the exception type even know you caught the exception with a catch all?
Example:
try
{
SomeBigFunction();
}
catch(...)
{
//Determine exception type here
}
| You can actully determine type inside a catch(...), but it is not very useful:
#include <iostream>
#include <exception>
class E1 : public std::exception {};
class E2 : public std::exception {};
int main() {
try {
throw E2();
}
catch( ... ) {
try {
... |
562,209 | 562,282 | typedef std containers? | I wanted to do
typedef deque type; //error, use of class template requires template argument list
type<int> container_;
But that error is preventing me. How do I do this?
| You can't (until C++0x). But it could be emulated with:
template<typename T>
struct ContainerOf
{
typedef std::deque<T> type;
};
used as:
ContainerOf<int>::type container_;
|
562,313 | 588,860 | Automatically display vertical scrollbar in multiline text edit control | On a windows mobile device I have a mutliline text edit control that is set to read-only and has some static text displayed during it's display lifetime. I would like to only display a vertical scrollbar when it's actually useful (i.e. the text is larger than the display).
I can't easily figure out if the text is to l... | This is how I solved this problem.
First off:
It only works with read-only mode of a edit control (as you don't want the text to change often).
I think is specific to Windows Mobile MFC, big windows can handle this a lot better.
The solution is very very hacky.
Solution:
I have a standard CEdit bound to the control... |
562,482 | 562,562 | How to manually decorate linker names in MSVC 2005? | Is there any way to manually decorate function names in MS C++? I'm going to guess any solution would be Microsoft-specific, and I'm cool with that.
Alternatively, is there a way to declare the function "??_M@YGXPAXIHP6EX0@Z@Z" so the compiler can understand it? FYI, undname lists it as:
void _ _ stdcall `eh vector... | If you declare your function as extern "C" and use the linker option that disables underscore prefix, the name you give in the code is the name you'll have in the .obj file. But this won't solve all your problems, since the compiler will balk when you try to declare a function with special characters in the name.
I gue... |
562,588 | 562,640 | Overriding function with enum/int | If there was a base class DeriveMe that had a function virtual void DoSomething(int) and a class that inherits DeriveMe called DerivedThat that had a function void DoSomething(SomeEnum)...would the DerivedThat override the base class DoSomething because enums evaluate to ints during compile time in C++?
I could try thi... | No, DerivedThat will hide the function from the base class, since the signatures don't match. enums do not evaluate to int, as they are a distinct type.
See the C++ FAQ, sections 23.9 and 29.19.
|
562,620 | 562,649 | What advantages are there to developing a Win32 app in C++ over a .NET app in C#? | I learned windows programming using Visual C++, and the Win32 API. Nowadays, it seems most apps are being developed in .NET using C#. I understand that most of the time there isn't much performance difference between native code and managed code. So I'm wondering, if I were to start writing a new desktop app today, is ... |
Performance (certain situations, such as graphics)
Memory footprint (as Mancuso said)
Use of existing libraries
No need for a runtime
Finer control
To list a few.
However, you may also want to look at the question from the opposite angle to fairly evaluate which language to use.
Additionally, you could use C++/CLI to... |
562,701 | 562,773 | Best way to determine if two path reference to same file in Windows? | How would I compare 2 strings to determine if they refer to the same path in Win32 using C/C++?
While this will handle a lot of cases it misses some things:
_tcsicmp(szPath1, szPath2) == 0
For example:
forward slashes / backslashes
relative / absolute paths.
[Edit] Title changed to match an existing C# question.
| Open both files with CreateFile, call GetFileInformationByHandle for both, and compare dwVolumeSerialNumber, nFileIndexLow, nFileIndexHigh. If all three are equal they both point to the same file:
GetFileInformationByHandle function
BY_HANDLE_FILE_INFORMATION Structure
|
562,973 | 563,373 | What are the symptoms of a stack overflow in a C++ program? | I just ran into an issue where a stack overflow in a threaded c++ program on HPUX caused a SEGV_MAPERR when a local object tried to call a very simple procedure. I was puzzled for a while, but luckily I talked to someone who recognized this as a stack size issue and we were able to fix the problem by increasing the st... |
How can I recognize when the stack overflows?
If you know the stack size, where the stack starts and the direction it grows in memory, you can simply check the address of the stack pointer and see if it past the end of the stack. C++ does not allow direct access to the stack pointer. You could easily write a small fu... |
563,000 | 567,886 | Can optimizations affect the ability to debug a VC++ app using its PDB? | In order to be able to properly debug release builds a PDB file is needed. Can the PDB file become less usable when the compiler uses different kinds of optimizations (FPO, PGO, intrinsic functions, inlining etc.)? If so, is the effect of optimization severe or merely cause adjacent lines of code to get mixed up?
(I'm ... | Yes, optimized code is less debuggable. Not only is some information missing, some information will be very misleading.
The biggest issue in my opinion is local variables. The compiler may use the same stack address or register for multiple variables throughout a function. As other posters mentioned, sometimes even ... |
563,168 | 563,177 | monitor a program's memory usage in Linux | Are there any tools available in Linux which graphically or textually display memory usage for a program? For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being insta... | It's not exactly what you are looking for, but have a look at Valgrind.
|
563,221 | 563,320 | Is there an implicit default constructor in C++? | In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this ... | If you do not define a constructor, the compiler will define a default constructor for you.
Construction
The implementation of this
default constructor is:
default construct the base class (if the base class does not have a default constructor, this is a compilation failure)
default construct each member variable in t... |
563,414 | 563,445 | How do you debug heavily templated code in c++? | I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.
What tips or advice can... | For the STL at least there are tools available that will output more human-friendly error messages. See http://www.bdsoft.com/tools/stlfilt.html
For non-STL templates you'll just have to learn what the errors mean. After you've seen them a dozen times it becomes easier to guess what the problem is. If you post them her... |
564,100 | 564,217 | Checking the value of a Lua stack item from C++ | how do I check the value of the top of the stack in Lua?
I have the following C++ code:
if (luaL_loadfile(L, filename) == NULL) {
return 0;// error..
}
lua_pcall(L,0,0,0); // execute the current script..
lua_getglobal(L,"variable");
if (!lua_isstring(L,-1)){ // fails this check..
lua_... | The likely problem is that luaL_loadfile() is documented to return the same values as lua_load() or one additional error code. In either case, the return value is an int where 0 means success and a nonzero value is an error code.
So, the test luaL_loadfile(...) == NULL is true if the file was loaded, but the code calls... |
564,469 | 564,491 | What is a good & free game engine? | For C++, Java, or Python, what are some good game + free game engines that are easy to pick up?
Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.
| For my Computer Graphics course in College we used the open source OGRE 3D engine. Not only is this an extremely robust 3D engine but it was a blast!
Develop a medium sized game using it and you will get a good taste of many of the different game programming specialties. You'll find yourself doing 3d modeling, sound ... |
564,480 | 564,559 | Embedding: mono vs lua | I am interested in hearing about peoples experience with embedding mono (open source implementation of .NET) in a C/C++ application. How is it to distribute such an application and what are the dependencies? I have tested on OS X and mono comes as a huge framework (hundreds of MB). Do users of my app all need this big ... | You should probably also take a look at Mono's Small Footprint page that describes how you can embed a smaller runtime. Heck, they do it themselves with Moonlight.
I hope that helps.
|
564,829 | 565,908 | Launching a .Net winforms application interactively from a service | Environment - VS2008, Vista SP1.
I have written a process management service which can launch applications either in session 0 or the interactive console (usually 1). Please note this is NOT the normal mode of operation, it's for in-house debug purposes only. In the field, these processes will be safely hidden away in ... | Despite the evident hysteria there is nothing wrong with launching an application from a service into an interactive session provided it is done with the same privileges as the interactive user or lower. Since you are launching as the interactive user there can be no privilege escalation.
What you are doing does work. ... |
564,933 | 565,428 | C++ Header To Source? | I'm programming in C++ CLI with VS.Net C++ 2008. I'm seeking a tool that can create my C++ source definitions (*.cpp) from the header files. Does such a tool exist? please advise, thanks.
| For pure C++ code, if its possible to add a 3rd party generator to the VS.Net frame work, then I would strongly recommend: lzz.
This tools takes a text file as input, and will provide a header and source file for you as appropriate. The following is the basic example from the web page:
// A.lzz
class A
{
public:
in... |
565,056 | 565,087 | What is your favorite cross-platform solution to access multiple different databases (MySQL, Oracle...) in C/C++? | I am writing a simple C++ application which might be installed on Linux or Windows, and which will connect to a database. I want my application to be compatible at least with Oracle and MySQL (or PostgreSQL).
Which C or C++ library would you recommend to handle the database queries: I am open to any library, whether i... | I enjoy using SOCI, it's very C++ like. When it comes to performance with respect to Oracle database, it's comparable with native OCI. It provides backend to some RDBMS:
Oracle
PostgreSQL
MySQL
And some more in the CVS repository.
It's fairly simple to use, the documentation is thorough and rationale is pretty clear.... |
565,360 | 565,474 | Overloading, strings, and default parameters | Refactoring legacy code, I came across this function (pseudocode):
int getMessage( char * buffer, int size = 300 );
Gee, look at that buffer just waiting to overflow. So I came up with a function using std::string, and thought it would be nice to use function overloading:
int getMessage( std::string & buffer );
So fa... | As always, once the problem is solved, the solution is painfully trivial and should have been obvious all along.
So I came up with a function using std::string...
...in my working directory, which compiled just fine, but -I and -L in my makefile were still pointing at the previous version of the library, which was bl... |
565,371 | 566,361 | How to load a c++ dll file into Matlab | I have a C++ dll file that uses a lot of other c++ librarys (IPP, Opencv +++) that I need to load into matlab. How can I do this?
I have tried loadlibrary and mex. The load library does not work.
The mex finds the linux things (platform independent library) and tries to include them. And that does not work.
Does anyone... | loadlibrary should work. I use it all the time to call functions from dlls written in C++ with C wrappers.
What errors are you getting when you try to use loadlibrary?
Make sure that the exported functions of the dll are C functions, not C++ functions. If not, then write C wrappers.
More info on exactly what you ar... |
565,459 | 565,523 | C++ wrapper with same name? | How can I do a wrapper function which calls another function with exactly same name and parameters as the wrapper function itself in global namespace?
For example I have in A.h foo(int bar); and in A.cpp its implementation, and in B.h foo(int bar); and in B.cpp foo(int bar) { foo(bar) }
I want that the B.cpp's foo(bar)... | does B inherit/implement A at all?
If so you can use
int B::foo(int bar)
{
::foo(bar);
}
to access the foo in the global namespace
or if it does not inherit.. you can use the namespace on B only
namespace B
{
int foo(int bar) { ::foo(bar); }
};
|
565,516 | 565,578 | What is the purpose of Browse Information generated by Visual Studio | I got a huge C++ third-party project with set of project in one solution. So build time is rather long and Browse Information generation takes a lot too. So what is the purpose of Browse Information? What functionality will be lost if i disable Browse information generation?
| Visual Studio 6 required browse information to do the things that Doug T. mentioned.
Newer versions of visual studio can use the browse information file, but by default use a newer Intellisense database. For those versions, there is basically an Intellisense daemon that builds the database in the background instead ... |
565,765 | 566,465 | implementing operator== when using inheritance | I have a base class which implements the == operator.
I want to write another class, inheriting the base class, and which should reimplement the == operator.
Here is some sample code :
#include <iostream>
#include <string>
class Person
{
public:
Person(std::string Name) { m_Name = Name; };
bool operator==(const P... | What you want to do is essentiall "virtualize" the comparison operator.
Since operators cannot be virtual (operators can be virtual), you will need to delegate it to something else. Here's one possible solution.
class Person
{
public:
/* ... */
bool operator==(const Person& rhs)
{
return ... |
565,804 | 642,638 | max value for SO_RCVBUF in Windows? | Quick question, wondering if anyone knew what the limit is for SO_RCVBUF under Windows.
| SO_RCVBUF in winsock is not limited by the TCP window size. At least for pre-Vista stacks. It would be limited by non-paged pool availability, which is a whole different topic.
So you can make it quite big, if you want to.
Obligatory unsolicited advice: If you are using a large buffer because you are receiving infrequ... |
565,824 | 566,553 | Can someone give me an example of a Unmanaged C++ HTML Client with proxy support? | Can someone give me an example of a Unmanaged C++ HTML Client with proxy support?
I want to do some get and posts inside my unmanaged c++ programs, ideally I would like to allow for proxy server configuration, or just use the IE defaults.
I am not looking for hand outs, just something to go by, as I can't seem to find ... | Call WinHttpGetIEProxyConfigForCurrentUser to get the proxy configuration and then use the HTTP stack of your choice. I would avoid implementing your own psuedo HTTP stack, getting it right is more work then you probably think.
|
565,938 | 565,957 | What container can I use to write binary? | I want to write a c array into a container and i prefer to modify it if possible.
I was thinking of using vector but it does seem to have a write(*pchararray, len); function. String looked like the next best thing but that too doesnt have a write function?
| Given
char myarray[10];
You can use an STL iterator:
vector <char> v;
copy(myarray, myarray + 10, back_inserter(v));
You can use a constructor:
vector <char> v(myarray, myarray + 10);
You can resize and copy:
vector<char> v(10);
copy(myarray, myarray + 10, v.begin());
(and all these work similarly for string)
Thank... |
566,037 | 570,612 | Filtering Eclipse's C++ Content Assist | I'm using Eclipse Ganymede (version 3.4.1) with a C++ project. Is there some way to filter the content assist list to only show methods and fields that are available in the current context?
If not, why not? Is there ever a situation where I would want to access the private fields, etc. in an object?
| Doesn't look like it. There are at least a couple of bugs open regarding this. You're lucky it shows too much! It never seems to assists in any way for me.
The latest CDT (at the time of writing Helios, with CDT version 7.0.0.201006141710) has the 2nd of those bugs fixed. However private member variables still showed u... |
566,040 | 566,072 | Mac OS X equivalent for TerminateProcess(GetCurrentProcess,0); | I am looking for a simple and uncatchable way to terminate the Mac port of my C++ application. In Windows I was using
TerminateProcess(GetCurrentProcess, 0);
What's the equivalent command I can use with Mac OS X / XCode / GCC?
| Actually you want _exit if you want to have the same semantics as TerminateProcess. exit semantics are more closely aligned with ExitProcess.
|
566,078 | 583,084 | What's the best way to parse RSS/Atom feeds for an iPhone application? | So I understand that there are a few options available as far as parsing straight XML goes: NSXMLParser, TouchXML from TouchCode, etc. That's all fine, and seems to work fine for me.
The real problem here is that there are dozens of small variations in RSS feeds (and Atom feeds too), so supporting all possible permutat... | "Best" is relative. The best performance you'll need to go the SAX route and implement the handlers. I don't know of anything out there open source available (start a google code project and release it for the rest of us to use!)
Whatever you do, it's probably a really bad idea to try and load the whole XML file int... |
566,225 | 566,654 | How to compile windows base program with eclipse cdt(using VIsual Studio compiler) | i'd like to compile (debugging if possible) windows program in eclipse cdt with microsoft copmiler.
It's better to support eclipse tool-chain (in eclipse cdt)
It's impossible to find this solution in google, except using mingw's make and Visual Studio Makefile..
Are there anyone to have solution with this problem?
| You want to use Wascana, an Eclipse/CDT distro targeted at Windows-development. Unfortunately the Windows-support is not complete; since it lacks a proper debugger.
|
566,587 | 567,479 | How to find the cause for a USER 44 PANIC? | One of the products we develop is a phone app for nokia phones done in C++ and Symbian, we started getting "random" crashes a while a ago with a USER 44 panic.
I am pretty new to the symbian environment so I am looking for tools and recommendations to help finding the root of this bug.
Is there a equivalent of a "stac... | From http://www.symbian.com/developer/techlib/v9.1docs/doc_source/reference/N10352/UserPanics.html:
This panic is raised by the Free() and FreeZ() member functions of an RHeap.
It is caused when the cell being freed overlaps the next cell on the free
list (i.e. the first cell on the free list with an address higher tha... |
566,603 | 566,623 | How to reach iteratively few variables which names differ only by number in C++? | I need a method helping me, to reach variables named like "comboBox1", "comboBox2" etc each by each in a loop. I'd like to change code like:
//proceed comboBox1
//proceed comboBox2
//proceed comboBox3
//proceed comboBox4
//proceed comboBox5
//proceed comboBox6
Into:
for (int i = 1; i < numberOfBoxes; i++) {
//proc... | The simplest solution is to put them all in an array and iterator over that:
// I've made up a type, but you get the idea.
std::vector<ComboBox *> combos;
combos.insert(comboBox1);
combos.insert(comboBox2);
combos.insert(comboBox3);
combos.insert(comboBox4);
combos.insert(comboBox5);
combos.insert(comboBox6);
Now you ... |
567,142 | 567,264 | public inheritance and tlb files | Say you have two assemblies (two dlls). The first contains a class called Base and the second contains a class called Derived which publicly inherits from Base.
When I use the tlb files to create C++ classes in Visual Studio 2005, I get Base and Derived classes, but one is not a subclass of the other. There doesn't se... | I'm assuming here, that the two assemblies communicate one with the other via COM, if that is indeed the case then you are correct, there is no IS-A relationship in COM in regard to CLASS inheritance, only in regard to Interface inheritance.
If you were to define an interface IBase and IDerived which derives from IBas... |
567,323 | 567,380 | Learning C++ Language | I am a .net c# programmer but I want to learn .NET C++ also. I am a beginner for c++. Is there any site, book, or Video Tutorials from beginner to expert?
| There's no such thing as ".Net c++".
Maybe you mean C++/CLI, which is Microsoft's language specification intended to supersede Managed Extensions for C++ (See Wikipedia). Managed extensions to C++ are its inferior and now defunct ancestor [thanks @dp for your comment].
Bear in mind when you choose your learning materia... |
567,626 | 567,686 | Unable to find operator via implicit conversion in C++ | When writing a class to act as a wrapper around a heap-allocated object, I encountered a problem with implicit type conversion that can be reduced to this simple example.
In the code below the wrapper class manages a heap-allocated object and implicitly converts to a reference to that object. This allows the wrapper ob... | It fails because you're trying to resolve an operator of your wrapper<T> class that doesn't exist. If you want it to work without the cast, you could put together something like this:
template<typename X> wrapper<T> &operator <<(X ¶m) const {
return t << param;
}
Unfortunately I don't know of a way to resolve... |
567,682 | 567,714 | Online compilers/runtime for Java, C++, Python and ObjC? | Does anyone know of a good online compiler/runtime (for C++, Java, Python, ObjC etc.) that I can access on the web?
What I'm looking for is something that would allow me to type in a program in a web form and to run the program and see the results online.
(Let's not get into the why for now. Suffice it to say for the ... | http://codepad.org/
codepad.org is an online
compiler/interpreter, and a simple
collaboration tool. Paste your code
below, and codepad will run it and
give you a short URL you can use to
share it in chat or email.
Languages:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
S... |
567,788 | 567,819 | C++ preprocessor unexpected compilation errors | Please look at the following file: (it is a complete file)
#ifndef TEES_ALGORITHM_LIBRARY_WRAPPER_H
#define TEES_ALGORITHM_LIBRARY_WRAPPER_H
#ifdef _TEES_COMPILE_AS_LIB
#include <dfa\Includes\DFC_algorithms.hpp>
#include <DFA\FuzzyClassifier\FuzzyAlgorithmIntialization\InitFuzzyAlgorithm.hpp>
typedef teesalgorithm::te... | It could be that the problem is in the included files (if there actually are unbalaced #if/#endifs.
I would try preprocessing with another compiler. You can use gcc for that, doesn't matter it wouldn't compile. Just get gcc (or MinGW if you're on Windows) and run
cpp -Iinclude_direcories your_file
Or, if you don't lik... |
568,218 | 568,226 | How do I divide two integers inside a double variable? | I am working on a lab for school that runs 10 trails of 10000 5 card hands. I have to find flushes and pairs in each hands. I have to find the percentage of pairs and flushs per trail.
My problem is when I try to get the percentage of a pair of one trail for example
double percent = total_pairs/10000;
or
double per... | Is "total_pairs" an int? If so, the divide is done as integer division. You need to explicitly cast one of the numbers to a double (and the other will be automatically promoted to double):
double percent = ((double)total_pairs)/10000; // or just simply 10000.0
|
568,524 | 568,528 | c++ outputting and inputting a single character | I am writing a program in c++ which implements a doubly-linked list that holds a single character in each node. I am inserting characters via the append function:
doubly_linked_list adam;
adam.append('a');
This function is implemented as follows:
//Append node
node* append(const item c){
//If the list is... | Where are you assigning the value c in the append() function? I fear you may have concentrated too much on the doubly-linked-list part and not enough on the storing-data part. :)
|
568,560 | 568,579 | Possible memory leak? | Okay, so I have two classes, call them A and B--in that order in the code. Class B instantiates class A as an array, and class B also has an error message char* variable, which class A must set in the event of an error. I created a third class with a pure virtual function to set the errorMessage variable in B, then mad... |
reportError() should be declared virtual in switchSystem, as it is in errorContainer.
char* should instead be std::string to avoid all of that needless work.
Is there some reason that you can't use an std::vector<switchObject> instead of new[]?
You shouldn't delete[] errorMessage when it points to a static literal str... |
568,596 | 568,627 | Simple Makefile Problem (with a simple dependency) | I have 4 '.cpp' files and 1 header files:
Tools.cpp
Code1.cpp
Code2.cpp
Code3.cpp
and Tools.hh
Now all Code1.cpp, Code2.cpp, Code3.cpp
use functions stored in Tools.cpp.
Currently, what I do to compile all of them is using
this simple shell script:
#!/bin/bash
echo "compiling Code1.cpp";
g++ Code1.cpp Tools.cpp -o Co... | In these targets:
Code1: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
The resulting command will be:
g++ Tools.cpp Code1.cpp Code2.cpp Code3.cpp Tools.hh makefile -o Code1
This is clearly not what you want. g++ is attempting to compile both the header file and the makefile and doesn't know what to do with the ... |
568,668 | 568,688 | What's your favorite g++ option? | I am a newbie in C++ programming.
When compiling I never use any option.
This is my day to day command:
g++ MyCode.cc -o MyCode
For safety practice what's the best option
to use?
| g++ -W -Wall -Werror
Will display all errors and warnings possible and treat them as errors.
|
568,804 | 568,817 | Do you have any good advice/links to a set of coding standards or best practices to follow? | For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original ... | Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
|
569,073 | 569,125 | C++ std::map of template-class values | I'm attempting to declare a Row and a Column class, with the Row having a private std::map with values pointing to a templated Column. Something like this:
template <typename T> class DataType {
private:
T type;
};
template <typename T> class Field {
private:
T value;
DataType<T> type;
};
class Row {
... | Field alone is not a type, but a template which can generate a family of types, such as Field<int> and Field<double>. All these fields are not related such that the one is somehow derived from the other or such. So you have to establish some relation between all these generated types. One way is to use a common non-tem... |
569,110 | 569,151 | Why is memory still accessible after std::map::clear() is called? | I am observing strange behaviour of std::map::clear(). This method is supposed to call element's destructor when called, however memory is still accessible after call to clear().
For example:
struct A
{
~A() { x = 0; }
int x;
};
int main( void )
{
std::map< int, A * > my_map;
A *a = new A();
a->x = 5;
my_m... | std::map does not manage the memory pointed to by the pointer values - it's up to you to do it yourself. If you don't want to use smart pointers, you can write a general purpose free & clear function like this:
template <typename M> void FreeClear( M & amap )
for ( typename M::iterator it = amap.begin(); it != ama... |
569,481 | 569,556 | Platform-independent concurrent programming libraries for C++ | I am familiar with concurrent programming in Java which provides a lot of tools for this. However, C++ concurrent programming isn't so easy to start using.
What is the best way to start programming concurrently on C++? Are there any nice libraries which wrap concurrent programming primitives and provide you with more h... | There are several choices:
ACE which provides some concurrency constructs
Intel Threading Building Blocks
boost::threads
OpenMP
Qt Threading libraries
|
569,950 | 589,883 | What causes Visual Basic Run-time error -2147319765 (8002802b) in Excel when an ActiveX control has been instanced? | I have created an ActiveX control using C++. I use Visual Basic code to instance the control in an Excel worksheet. I can only run the VB script once, subsequent runs cause the following runtime error when attempting to access the 'ActiveSheet' variable:
Microsoft Visual Basic
Run-time error '-2147319765 (8002802b)'... | After talking to Microsoft I found out the cause of the problem I was having.
When creating an ActiveX control using the VS 2005/2008 wizard you need to check the 'Connection points' check box in the 'Options' page. This adds, among other things, IConnectionPointContainerImpl as a base class for your ATL class, which ... |
570,669 | 570,694 | Checking if a double (or float) is NaN in C++ | Is there an isnan() function?
PS.: I'm in MinGW (if that makes a difference).
I had this solved by using isnan() from <math.h>, which doesn't exist in <cmath>, which I was #includeing at first.
| According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN.
Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.
For any compiler which claims to use... |
570,693 | 570,717 | Does using boost pointers change your OO design methodology? | After switching from C++ to C++ w/boost, do you think your OOD skills improved?
Do you notice patterns in "Normal" C++ code that you wouldn't consider that you've switched, or do you find that it enables a more abstract design?
I guess I'm really wondering if you just use it as a tool, or if you change your entire ap... | In a project in C++ I was doing about six years ago, we implemented our own boost-like automatic pointer scheme. It worked pretty well, except for the various bugs in it. (Sure wish we had used boost...)
Nonetheless, it really didn't change how we developed code. Object oriented design, with or without managed poin... |
571,359 | 571,397 | how do I set the proper initial locale for a C++ program on Windows? | I'm fairly new to localized programming, and I'm trying to figure out how to set the proper initial locale for a newly-launched unmanaged C++ application (from within the app).
As far as I can tell, new applications start with the C locale, rather than the proper regional locale (English, German, etc). So what I need t... | setlocale() is C, not C++. I vaguely remember seeing interference between the two on VC6, but that was a bug. Normally, setlocale() affects the behavior of the C functions only.
In C++, localization is controlled by the std::locale class. By default, locale-sensitive operations use the global locale, which is obtained ... |
571,394 | 571,405 | How to find out if an item is present in a std::vector? | All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.
if ( item_present )
do_this();
else
do_that();
| You can use std::find from <algorithm>:
#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()
This returns an iterator to the first element found. If not present, it returns an iterator to... |
571,568 | 571,589 | Is there a way to include a header in every compilation unit without modifying every source file? | Given the following:
large project with thousands of C++ source files
no common header file (no one header that's included in every source file)
said project is compiled with g++ and managed by make
Is there any way to include a definition (e.g. macro) into every compilation unit without modifying every source file t... | From man gcc:
-include file
Process file as if "#include "file"" appeared as the first line of
the primary source file. However, the first directory searched for
file is the preprocessor's working directory instead of the directory
containing the main source file. If not found there, it is
searched ... |
571,652 | 571,728 | What is the best way to handle multiple object dependencies in C++? | I'm building a C++ application, and I've got several utility objects that all of my classes need to use. These are things like the logging object, the global state object, the DAL object, etc...
Up until this point, I've been passing all of these objects around as references into my class constructors.
For example:
... | You could make use of the Service Locator pattern. This article introduces both dependency injection (which you are currently using) and service locator.
However, consider this: the idea of dependency injection is to have a system where each component has a well-defined responsibility and minimizes knowledge of other c... |
571,799 | 572,012 | Exporting functions from C++ dll to C# P/Invoke | I have built a C++ dll that I would like to call from C# code. I'm able to call one function, but the other throws an exception when the C# code tries to load the dll.
The header looks like this:
extern "C" __declspec(dllexport) BOOL Install();
extern "C" __declspec(dllexport) BOOL PPPConnect();
This produces a dll wi... | Are you using a .def file in your dll project to export those functions? If so, remove it and try again. This is just a guess because it looks like your exports are not what they should be when you do an extern "C" declspec(dllexports).
I tried this out with a simple C++ dll using
extern "C" __declspec(dllexport) BOOL... |
571,890 | 571,899 | container for quick name lookup | I want to store strings and issue each with a unique ID number (an index would be fine). I would only need one copy of each string and I require quick lookup. I check if the string exist in the table often enough that i notice a performance hit. Whats the best container to use for this and how do i lookup if the string... | I would suggest tr1::unordered_map. It is implemented as a hashmap so it has an expected complexity of O(1) for lookups and a worst case of O(n). There is also a boost implementation if your compiler doesn't support tr1.
#include <string>
#include <iostream>
#include <tr1/unordered_map>
using namespace std;
int mai... |
572,255 | 572,264 | Why should/shouldn't I use the "new" operator to instantiate a class, and why? | I understand that this may be construed as one of those "what's your preference" questions, but I really want to know why you would choose one of the following methods over the other.
Suppose you had a super complex class, such as:
class CDoSomthing {
public:
CDoSomthing::CDoSomthing(char *sUserName, char... | Prefer local variables, unless you need the object's lifetime to extend beyond the current block. (Local variables are the second option). It's just easier than worrying about memory management.
P.S. If you need a pointer, because you need it to pass to another function, just use the address-of operator:
SomeFuncti... |
572,684 | 572,766 | Conditional Inclusion/Exclusion of Data Members Inside Class Templates | I want to optimize my Vector and Matrix classes (which are class templates to be exact) using SIMD instructions and compiler intrinsics. I only want to optimize for the case where the element type is "float". Using SIMD instructions requires touching the data members. Since I don't want to be bothered with the trouble ... | One solution that springs to mind is partially specialized templates, which is what Martin York posted, but with a twist.
I would recommend a special content_type-struct to supply the layout type, like so:
// content for non float types
template<typename T>
struct content_type {
typedef typename T member_type;
me... |
572,685 | 572,705 | In what scenarios should one declare a member function a friend? | In what kind of scenarios would we declare a member function as a 'friend function' ?..What exact purpose does 'friend function' which defies one of central concept of 'Encapsulation' of OOP serve?
| You would use a friend function for the same sort of reasons that you would use a friend class, but on a member function (rather than entire class) basis. Some good explanations are in this thread.
While friend functions and classes do violate encapsulation, they can be useful in some scenarios. For example, you may ... |
572,734 | 572,822 | Infile Handle in C++ (ala __DATA__ in Perl) | Does C++ have access to infile data through a filehandle? For example the typical idiom in Perl is:
while (<DATA>) {
chomp;
# do sth with $_
}
__DATA__
Foo
Bar
What's the way to do that in C++ ?
| I wouldn't say it's idiomatic as I've never seen it in any C++ code, but you can use C++ string stream and C pre-processor string pasting to treat a multi-line string as an input stream:
#include <sstream>
#include <iostream>
using namespace std;
const string data =
"once upon a time, " \
"a young lass calle... |
572,831 | 572,841 | Problem transmitting null character over sockets | I am writing a small Java server, and a matching client in C++, which implement a simple IM service over the STOMP protocol.
The protocol specifies that every frame (message that passes between server and client, if you will) must end with a null character, which in code I refer to as '\0', both in Java and in C++.
How... | Wether you are encoding text in ASCII or UTF-8, you convert your "letters" to a stream of bytes (byte encodings). You need to add a ZERO byte to the end of the message strings.
[Guessing] You may be using a high-level library with a method like "WriteLine(String line)" to send the data over the network. The documentati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.