question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,291,226 | 1,291,304 | What is an SDK? (C++) | Just in general terms, for a noobie. I apparently need an 'SDK' to install something; what is this?
| An SDK is a set of libraries which hold reusable code that you in turn use to develop applications. Whether those applications will run in Windows, on an XBOX, and iPhone, in a Flash application, etc. determine what SDK you should be using.
Take the iPhone for example. To write an iPhone application, you write code in ... |
1,291,324 | 1,291,519 | "Is there a better way?" Error 12029 with wininet on Windows Vista | I kept recieving error 12029 (ERROR INTERNET CANNOT CONNECT, The attempt to connect to the server failed.) when using the the MFC wininet classes on Windows Vista. The cause of the error was due to Windows Defender. Is there a better way to get around this than completely turning off Windows Defender? I tried turnin... | If Windows Defender displays a warning message after blocking your program, you should have the option to add your program to a list of "allowed items" which will allow it to run unencumbered while real time protection remains enabled. Admittedly, this is only a viable option if you are working with non-production/pers... |
1,291,338 | 1,300,352 | Write unicode string into file with CodeGear C++ Builder 2009 | I have just switched from Builder 6 to Builder 2009 and have a question.
How can I write unicode string to a file?
TBytes Preamble1 = TEncoding::Unicode->GetPreamble();
UnicodeString str1("string1");
int len = TEncoding::Unicode->GetByteCount(str1);
FileWrite( iFile,&Preamble1[0],Preamble1.Length );
FileWrite( iFile,... | My first question would be "What kind of file"?
Assuming it's a text file rather than binary, what kind of encoding do you want on the output? UTF-8 is usually a good choice, because it's supported by stuff like notepad, and for normal "Latin" characters, there's no overhead.
Personally, to write 'simple' text files, I... |
1,291,446 | 1,291,493 | Visual C++ versions of GCC functions | Are there Visual C++ versions of the following (in GCC)?
__builtin_return_address
__builtin_frame_address
Reference - http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html
If not, is there a way to emulate them?
Thanks.
| Here is a full list of the available Visual Studio 2008 Compiler Intrinsics. One of the ones you are specifically looking for here is _ReturnAddress... still looking for the other.
For walking the stack (and getting frame pointers), read the details on the Visual Leak Detector stack walking mechanism, which uses StackW... |
1,291,594 | 1,295,828 | Using libs/dlls compiled in Linux/MinGW in Visual Studio | Update: I get this warning when compiling: multiple '.text' sections found with different attributes
Hi,
I've compiled some libraries (.a and .dll) in Linux using the MinGW Cross Compiler. I can successfully link against them (.a) in Visual Studio 2008. However, when it runs (using .dll), it terminates with the address... | Found it.
http://www.mingw.org/wiki/MSVC_and_MinGW_DLLs
You have to have a def file and use the VC's lib tool to generate an import library.
|
1,292,138 | 1,292,157 | When to use extern "C" in C++? |
Possible Duplicate:
Why do we need extern “C”{ #include <foo.h> } in C++?
I have often seen programs coded like:
extern "C" bool doSomeWork() {
//
return true;
}
Why do we use an extern "C" block? Can we replace this with something in C++? Is there any advantage to using extern "C"?
I do see a link explaining t... | extern "C" makes names not mangled.
It used when:
We need to use some C library in C++
extern "C" int foo(int);
We need export some C++ code to C
extern "C" int foo(int) { something; }
We need an ability to resolve symbol in shared library -- so we need to get rid mangling
extern "C" int foo(int) { something; }
///
... |
1,292,241 | 1,292,387 | Creating custom dictionaries in aspell with the C API | I am using aspell in my application for spell checking (a c/c++ app), and I want to use it to find best alternatives in a custom work list. I don't want to use a standard dictionary, as I only want to find words in my word list. I can find ways of adding words to a dictionary (aspell_speller_add_to_personal and aspel... | I did this about three years ago. It was in a convoluted way that included creating a dictionary data structure from an existing file, deleting it and adding words using
aspeller::Dictionary::add(). It was tough.
If you do not have to use aspell, you may try hunspell, which may or may not be easier to customize.
See... |
1,292,297 | 1,292,669 | boost::array not compiling on VS 2005 | Sorry this is probably a stupid question, as I couldn't find anything at all on google on the subject. Anyways I'm trying to compile some source code, that uses boost::array with visual studio 2005, as a Win32 console application (not clr), however for some reason that escapes me Visual Studio still considers the word ... | This simple program compiled and worked perfectly in my VC++ 2005:
#include <iostream>
#include <boost/array.hpp>
int
main()
{
const int size = 3;
boost::array<double,size> myArray;
myArray[0] = 23.43f;
myArray[1] = 24.00f;
myArray[2] = 23.50f;
double sum = 0.0;
for (size_t i = 0; i ... |
1,292,426 | 1,292,443 | Is there any well-known paradigm for iterating enum values? | I have some C++ code, in which the following enum is declared:
enum Some
{
Some_Alpha = 0,
Some_Beta,
Some_Gamma,
Some_Total
};
int array[Some_Total];
The values of Alpha, Beta and Gamma are sequential, and I gladly use the following cycle to iterate through them:
for ( int someNo = (int)Some_Alpha; someN... | enum Some
{
Some_first_ = 0,
Some_Alpha = Some_first_,
....
Some_last_
};
Doing such you can grant first & last never changes order
|
1,292,511 | 1,292,745 | Using stable_sort() to sort doubles as ints | I have a huge array of ints that I need to sort. The catch here is that each entry in the list has a number of other associated elements in it that need to follow that int around as it gets sorted. I've kind of solved this problem by changing the sorting to sort doubles instead of ints. I've tagged each number before i... | Since you say you're not familiar with vectors (you really should learn STL containers ASAP, though), I assume you're playing with arrays. Something along these lines:
int a[] = { 3, 1, 2 };
std::stable_sort(&a[0], &a[3]);
The third optional argument f of stable_sort is a function object - that is, anything which can ... |
1,292,718 | 1,292,773 | about the cost of virtual function | If I call a virtual function 1000 times in a loop, will I suffer from the vtable lookup overhead 1000 times or only once?
| The Visual C++ compiler (at least through VS 2008) does not cache vtable lookups. Even more interestingly, it doesn't direct-dispatch calls to virtual methods where the static type of the object is sealed. However, the actual overhead of the virtual dispatch lookup is almost always negligible. The place where you somet... |
1,292,786 | 1,292,938 | Is Updating double operation atomic | In Java, updating double and long variable may not be atomic, as double/long are being treated as two separate 32 bits variables.
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733
In C++, if I am using 32 bit Intel Processor + Microsoft Visual C++ compiler, is updating double (8 byte) operati... | This is hardware specific and depends an the architecture. For x86 and x86_64 8 byte writes or reads are guaranteed to be atomic, if they are aligned. Quoting from the Intel Architecture Memory Ordering White Paper:
Intel 64 memory ordering guarantees
that for each of the following
memory-access instructions, the... |
1,292,927 | 1,293,103 | wait for works item to complete pooled using QueueUserWorkItem (not .NET) | I have some work items pooled using the legacy QueueUserWorkItem function (I need to support OSs earlier than vista, so
for( <loop thru some items >)
{
QueueUserWorkItem( )
}
I need to wait on these before proceeding to the next step.
I've seen several similar answers...but they are in .NET.
I'm thinking of usi... | AFAIK the only ways you can do this is to have a counter that is InterlockIncrement'ed as each task finishes.
You can then either do a
while( counter < total )
Sleep( 0 );
of the task can signal an event (or other sync object) and you can do the following
while( count < total )
WaitForSingleObject( hEvent, IN... |
1,292,995 | 1,294,006 | writing files and dirs using C++ | I'm working on a program that creates 2000 directories and puts a file in each (just a 10KB or so file). I am using mkdir to make the dirs and ofstream (i tried fopen as well) to write the files to a solid state drive (i'm doing speed tests for comparison).
When I run the code the directories are created fine but the f... | You open directories with opendir() but never close them with closedir() - I suspect there is a resource limit there too.
|
1,293,231 | 1,293,274 | stl ordering - strict weak ordering | Why does STL work with a comparison function that is strict weak ordering? Why can't it be partial ordering?
| A partial order would not be sufficient to implement some algorithms, such as a sorting algorithm. Since a partially ordered set does not necessarily define a relationship between all elements of the set, how would you sort a list of two items that do not have an order relationship within the partial order?
|
1,293,326 | 1,293,421 | Deleting pointer sometimes results in heap corruption | I have a multithreaded application that runs using a custom thread pool class. The threads all execute the same function, with different parameters.
These parameters are given to the threadpool class the following way:
// jobParams is a struct of int, double, etc...
jobParams* params = new jobParams;
params.value1 = 2;... | Let's turn this on its head: Why are you using pointers at all?
class Params
{
int value1, value2; // etc...
}
class ThreadJob
{
int jobID; // or whatever...
Params params;
}
class ThreadPool
{
std::list<ThreadJob> jobs;
void addJob(int job, const Params & p)
{
ThreadJob j(job, p);
jobs.push_bac... |
1,293,708 | 1,293,887 | Compile error using boost::concept_check | I'm trying to compile simple example to use the boost concept_check
Code is as follow:
#include <vector>
#include <complex>
#include <algorithm>
#include <boost/iterator.hpp>
#include <boost/concept_check.hpp>
template <class foo>
void my_do_sort(std::vector<foo>& v)
{
BOOST_CONCEPT_ASSERT((RandomAccessIterator<fo... | This was just compilation issue. I had to use boost namespace.
|
1,293,889 | 1,293,953 | Microsoft _stprintf warning | Why I get the following warning for the following code :)
Code:
_stprintf(m_szFileNamePath,_T("%s"),strFileName);
warning C4996: '_swprintf': swprintf has been changed to conform with the ISO C standard, adding an extra character count parameter. To use traditional Microsoft swprintf, set _CRT_NON_CONFORMING_SWPRINTF... | http://msdn.microsoft.com/en-us/library/ybk95axf%28VS.80%29.aspx
swprintf is a wide-character version of sprintf; the pointer arguments to swprintf are wide-character strings. Detection of encoding errors in swprintf may differ from that in sprintf. swprintf and fwprintf behave identically except that swprintf writes ... |
1,293,933 | 1,298,323 | Synchronizing access to variable | I need to provide synchronization to some members of a structure.
If the structure is something like this
struct SharedStruct {
int Value1;
int Value2;
}
and I have a global variable
SharedStruct obj;
I want that the write from a processor
obj.Value1 = 5; // Processor B
to be immediately visible to ... | All the other answers here seem to hand wave about the complexities of updating shared variables using mutexes, etc. It is true that you want the update to be atomic.
And you could use various OS primitives to ensure that, and that would be good
programming style.
However, on most modern processors (certainly the x86)... |
1,293,951 | 1,294,002 | Mix of template and struct | I have a template class defined as follow :
template <class T1, class T2>
class MyClass { };
In this class, I need a struct that contains one member of type T1. How can I do that ?
I tried the following, but it didn't work :
template <class T1, class T2>
class MyClass {
typedef struct {
T1 templateMember;
... | Just remove typedef:
template <class T1, class T2>
class MyClass {
struct myStruct{
T1 templateMember;
// rest of members
} ;
};
|
1,294,215 | 1,294,259 | Member function pointer calls copy constructor? | I'm trying to create a lookup table of member functions in my code, but it seems to be trying to call my copy constructor, which I've blocked by extending an "uncopyable" class. What I have is something like the following.
enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };
class Foo {
fun1(Bar b){ ... }
fun2(Bar b){ ... }... | Make them reference parameters.
enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };
class Foo {
fun1(Bar &b){ ... }
fun2(Bar &b){ ... }
...
void (Foo::*lookup_table[NUM_FUNS])(Bar &b);
Foo(){
lookup_table[FUN1_IDX] = &Foo::fun1;
lookup_table[FUN2_IDX] = &Foo::fun2;
}
void doLookup(int fun_num, Bar &b) ... |
1,294,417 | 1,294,460 | Using LD to link intermediate files | If I have a.o, b.o, and c.o, how do I make ld link them into d.o, which is then linked into my main object file? All that I want to have happen is that all the symbols in the input files get combined into one big output file.
| A concatenation of .o files is called a library. You create one
with the ar library utility:
ar rvs mylib.a a.o b.o c.o
You can then link against the library:
cc main.c mylib.a
|
1,294,465 | 1,298,481 | Print server - want to catch print command | How should i know at print server whether any client has fire any command. or any way to hook into printer driver at printing driver at server
What is print server ???
How print server work in Window???
How muliple client will send request to single print server???
Is any utility is running???
Can anybody clear me on ... | It seems Microsoft do provide some APIs for intercepting the print spool:
http://msdn.microsoft.com/en-us/library/ms802176.aspx
Good luck!
|
1,294,756 | 1,294,826 | Queue that uses a Stack | I am having trouble understanding a question. The question asks first to write a C++ class to represent a stack of integers, and that much is done. Here are my prototypes:
class Stack{
private:
int top;
int item[100];
public:
Stack() {top = -1;}
~Stack();
void push(int x) {item[++top] = x;}
int ... | I don't agree with the existing answer. Typically, a queue is First In First Out, while a stack is obviously Last In First Out. I can only think of an implementation using two stacks, popping the whole thing and adding all but the last item to the second stack.
Seems like a silly thing to do, but I guess it's for the s... |
1,294,805 | 1,308,893 | Transparent window containing opaque text and buttons | I'm creating a non-intrusive popup window to notify the user when processing a time-consuming operation. At the moment I'm setting its transparency by calling SetLayeredWindowAttributes which gives me a reasonable result:
alt text http://img6.imageshack.us/img6/3144/transparentn.jpg
However I'd like the text and close... | In order to do "proper" alpha in a layered window you need to supply the window manager with a PARGB bitmap by a call to UpdateLayeredWindow.
The cleanest way to achieve this that I know of is the following:
Create a GDI+ Bitmap object with the PixelFormat32bppPARGB pixel format.
Create a Graphics object to draw in th... |
1,294,819 | 1,295,080 | Can I convert the floating part of a double into an integer (without using string conversions)? | Example: If I have 7.2828, I just want to get the 2828 as an integer.
| Decimal is your friend...
Convert your number to a decimal and then do this.
decimal d = (decimal)7.2828;
int val = decimal.GetBits(d - decimal.Truncate(d))[0];
the neat thing about a decimal is that it stores the val as an int, and then just stores a decimal point position.
|
1,294,832 | 1,295,380 | What is the correct way to instantiate an object with an allocator? | I have implemented a custom allocator (to be used by STL containers within my memory debugging utility, without them using my overridden new operator). Within the memory debugger I use an instance of the same allocator class to allocate the objects I need to keep track of 'normal' memory allocations. It's all working f... | You can actually overload new and delete to take an allocator parameter, like so:
inline void *operator new(size_t sizeT, Allocator *&a) {
return a->allocate(sizeT);
}
inline void operator delete(void * mem, Allocator *&a) {
a->release(mem);
}
int main()
{
Allocator * a = new Allocator;
C *c = new(a) C;
c->... |
1,295,160 | 1,295,191 | C++ IP Address human-readable form | In C/C++, you can use the regular gethostbyname() call to turn a dotted-IP address string ("127.0.0.1" in the case of localhost) into a structure suitable for standard socket calls.
Now how do you translate it back? I know I can do some bit-shifting to get exactly which bit sets I want and just print those out, but is... | First of all, in new code you should generally prefer using getaddrinfo() to gethostbyname(), which is old and clunky and is tough to use to support both IPv4 and IPv6. See here: https://beej.us/guide/bgnet/html/multi/syscalls.html
Secondly, the function that does what you want is called inet_ntop.
|
1,295,199 | 1,295,286 | behavior of bool with non-boolean operators | What I really want is a ||= operator.
old_value = old_value || possible_new_value;
old_value ||= possible_new_value;
The second line is a compiler error (c++ doesn't have a ||= operator).
So what are my other options?
old_value += possible_new_value;
old_value |= possible_new_value;
While I'm on the subject how does ... | According to 4.7 (Integral conversions), paragraph 4, "If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one." In 4.12, "An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue o... |
1,295,773 | 1,295,798 | Header dependencies in qmake using MSVC Express | I'm using QtCreator on windows using MSVC compiler (the compiler from Visual c++ express edition) and qt 4.5.2 open source.
When I modify a header on the project and press build all, nothing is actually built, only If I modify a .cpp file the modified cpp is compiled.
That causes that every time that I have to change s... | Are your header files listed in the HEADERS variable in your .pro file? I think listing header files in HEADERS is also required to get classes within them MOC'ed.
**[edit]**Nevermind, I tested this out with Qt Creator 1.2.1 from the Qt 4.5.2 SDK on linux, and when I 'touch' a header file, the cpps it depends on are r... |
1,296,185 | 1,324,032 | Compile and optimize for different target architectures | Summary: I want to take advantage of compiler optimizations and processor instruction sets, but still have a portable application (running on different processors). Normally I could indeed compile 5 times and let the user choose the right one to run.
My question is: how can I can automate this, so that the processor i... | If you wish this to cleanly work on Windows and take full advantage in 64bit capable platforms of the additional 1. Addressing space and 2. registers (likely of more use to you) you must have at a minimum a separate process for the 64bit ones.
You can achieve this by having a separate executable with the relevant PE64 ... |
1,296,316 | 1,296,514 | How to get the end of a C++ string stream? | I'm adding functions to my (simple) log class to make it usable like a stream.
Currently, after some modifications, I got this (in my cpp):
// blah blah blah...
// note: here String is a defined as: typedef std::string String;
void Log::logMessage( const String& message )
{
logText(); // to be sure we flus... | You can create a temp object and use his destructor to catch the end of the statement:
following code should give you the basic idea
class Log
{
public:
class Sublog
{
public:
Sublog(const std::string& message)
{
std::cout << message;
}
void addText(const std::string& message)
{
s... |
1,296,506 | 1,296,604 | Getting a compile error : 0x2 trying to open file <vfdmsg> | I'm trying to build http://chitchat.at.infoseek.co.jp/vmware/vfd.html (VS 2008, Windows Server 2008 x64) however I'm getting the following error messages:
Error 1 error : 0x2 trying to open file <vfdmsg>. mc lib
Error 2 error PRJ0019: A tool returned an error code from "Compiling Message - L:\src\lib\vfdmsg.... | I've fixed this by noticing that the build step for vfdmsg.mc was:
mc $(InputName)
Where $(InputName) resolved to vfdmsg, not vfdmsg.mc
Fixed by replacing this with the following build step:
mc $(InputFileName)
|
1,296,674 | 1,296,757 | How to implement scoped iostream formatting? | I'd like to scope-limit the effect of I/O stream formatting in C++, so that I can do something like this:
std::cout << std::hex << ...
if (some_condition) {
scoped_iofmt localized(std::cout);
std::cout << std::oct << ...
}
// outside the block, we're now back to hex
so that base, precision, fill, etc. are restore... | Maybe something like the Boost I/O Stream State-saver library?
|
1,296,893 | 1,299,166 | Boost best practices? | I've used Boost graph library a fair amount but not much of the rest of it. I frequently see recommendations here to use parts of Boost (say, Boost's various smart pointers). Obviously Boost is good and good to use. It is also large or diverse. Does anyone know of a FAQ or decent best practices doc to help a knowledgea... | I learned the libraries I use by other developers suggesting certain libraries and me reading all the documentation I could find/needed to use the library.
However recently I bought this book, Beyond the C++ Standard, that introduces the most common parts of Boost. Even with reasonable boost experience I found this ... |
1,296,907 | 1,296,934 | Function template specialization with reference to pointer | I have a template function:
template<typename T>
void foo(const T& value) { bar(value); x = -1; }
I want to specialize it for a set of types:
template<>
void foo<char>(const char& value) { bar(value); x = 0; }
template<>
void foo<unsigned char>(const unsigned char& value) { bar(value); x = 1; }
It works ok. When I co... | Sure. Try this:
template<>
void foo<char*>(char* const& value) {...}
This is because const char* means pointer to const char, not a const pointer to char.
|
1,296,947 | 1,297,494 | How to create binary/hex dump of another process's memory? | I am having trouble finding a reasonable way to dump another process's memory to a file.
After extensive searching, I've been able to find a nice article at CodeProject that has *most* of the functionality I want:
Performing a hex dump of another process's memory. This does a good job of addressing permission issues a... | You're basically asking for a user process minidump. The Windows Debug Helper library has a ready made function for this, MiniDumpWriteDump.
There is a coarse control over the amount of the detail contained in the mini dump from the MINIDUMP_TYPE parameter passed in to the function. The most basic, MiniDumpNormal, wil... |
1,297,059 | 1,297,106 | C++: Callback typedefs with __stdcall in MSVC | This typedef:
typedef DWORD WINAPI
(* CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD);
compiles fine in BorlandCpp, however, when I compile it in msvc I have to remove WINAPI (which is just an alias for __stdcall):
typedef DWORD
(* CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD);
Why is ... | I believe on VC++ you need to put the calling convention inside the ()'s Here's an example on MSDN of using a calling convention inside a function pointer typedef.
typedef DWORD (WINAPI * CM_Open_DevNode_Key)(DWORD, DWORD, DWORD, DWORD, PHKEY, DWORD);
This should compile without problem.
|
1,297,205 | 1,297,210 | The C++ implicit this, and exactly how it is pushed on the stack | I need to know whether, when a class method in C++ is called, the implicit 'this' pointer is the first argument, or the last. i.e: whether it is pushed onto the stack first or last.
In other words, I'm asking whether a class method, being called, is taken by the compiler to be:
int foo::bar(foo *const this, int arg1, i... | This depends on the calling convention of your compiler and the target architecture.
By default, Visual C++ will not push this on the stack. For x86, the compiler will default to "thiscall" calling convention and will pass this in the ecx register. If you specify __stdcall for you member function, it will be pushed o... |
1,297,609 | 1,297,635 | Overloading friend operator << for template class | I'm trying to overload the operator << as a friend to a template class Pair, but I keep getting a compiler warning saying
friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function
for this code:
friend ostream& operator<<(ostream&, Pair<T,U>&);
it gives a second warning ... | You declare operator<< as returning an ostream&, but there is no return statement at all in the method. Should be:
template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
return out << v.val1 << " " << v.val2;
}
Other than that, I have no problems or warnings compiling your code under Visual ... |
1,297,688 | 1,297,708 | A simple C++ question on memory usage | What is the difference (memory wise) bewteen:
for(int x=0;x<100;x++)
{
int y = 1+x;
}
and
int y = 0;
for(int x=0;x<100;x++)
{
y = 1+x;
}
I've always wondered if they are the same or the first is a waste of memory?...
| Memory-wise, there is no difference. y is on the stack, wherever it's declared within the method. Here the only difference is the scope of y: in the second case, it is restricted to the body of the for loop; in the first, it isn't. This is purely at the language-level: again, y is allocated in exactly the same way, tha... |
1,297,710 | 1,299,806 | boost.thread dead-lock and self-deletion | I am using boost::thread_group to create(using
thread_group::create_thread()) and dispatch threads. In order to limit
the max thread numbers, at the end of each thread, I remove the thread
from the thread_group and delete the thread itself(so that I could
decide whether new threads need to be created). However it ... | Why don't you try to recycle the threads, since creation/destruction is expensive?
Code a thread pool class and send tasks to it. The pool will either queue the tasks if it has no more available threads, create threads if current_threads < max_threads or just use what thread is available.
Suggested implementation:
Fin... |
1,297,935 | 1,496,020 | Evaluate Expression in RAD Studio 2007's Watch | I know that most of you might have noticed now. When you try to evaluate an expression using watch on RAD Studio 2007, it does not evaluate.
For example, if I had a vector, I could not do "vecData.size()", if I do "vecData.size", it just gives an address.
Is there any other way to watch the size and view each element o... | If you disable the compiler optimisations in the project options, the debugger will then be able to evaluate vecData.size().
"Project Options->C++ Compiler->Optimizations->Disable all optimizations" set this option to "True".
This works for 2009, I believe it is the same for 2007.
|
1,298,003 | 1,298,011 | Calculate minimum area rectangle for a polygon | I have a need to calculate the minimum area rectangle (smallest possible rectangle) around the polygon.
The only input i have is the number of points in polygon.
I have the co-ordinates of the points also.
| Use the rotating calipers algorithm for a convex polygon, or the convex hull otherwise. You will of course need the coordinates of the points in the polygon, not just the number of points.
|
1,298,316 | 1,327,241 | Catching LoadLibrary() errors gracefully | I'm working on a piece of C++ software which runs on all Windows versions between Windows XP and Windows Vista. In my code, I developed a DLL which links against a standard library (the Qt library). Once my software is deployed, it's not unusual that the user doesn't have the exact same Qt build on his system but a sli... | Can MapAndLoad from ImageHLP.DLL may help. It returns a LOADED_IMAGE structure.
|
1,298,557 | 1,309,678 | Yet another linker issue | I'm having a linking issue with a basic C++ program. No, I'm not including .cpp files!
This is what's happening.
main.cpp:
#include "header.h"
#include <iostream>
int main() {
std::cout << "Hello!";
}
header.h:
#ifndef _HEADER_H
#define _HEADER_H
class Something {
public:
printContents();
};
#endif
something... | The problem was in a multi-installation of MinGW. I had one already installed, and when I got Qt on my computer, it had installed it's own MinGW. Bummer, I ported the code to my university's servers and it ran OK.
Bummer!!
Thanks everybody for the help, I will definitely follow your guidelines in the future.
Header na... |
1,298,750 | 1,298,760 | Access base class fn with same signature from derived class object | Is it possible to access a base class function which has the same signature as that of a derived class function using a derived class object?. here's a sample of what I'm stating below..
class base1 {
public:
void test()
{cout<<"base1"<<endl;};
};
class der1 : public base1 {
public:
void test()
{cout<<... | You need to fully qualify the method name as it conflicts with the inherited one.
Use obj.base1::test()
|
1,299,065 | 1,300,488 | Deleting a pointer a different places results in different behaviors (crash or not) | This question is a refinement of this one, which went in a different direction than expected.
In my multithreaded application, the main thread creates parameters and stores them:
typedef struct {
int parameter1;
double parameter2;
float* parameter3;
} jobParams;
typedef struct {
int ID;
void* param... | Just as a thought .. can you try
for (int i = 0; i < jobs.size(); ++i) {
delete (jobParams*)jobs[i].params;
}
newing a type jobParams and then deleteing a void* might be the cause of your problems.
Is there any reason you store params as a void* in jobData? I'd argue if you wish to have different types of jobPar... |
1,299,104 | 1,299,121 | basic pointer question in c++ program | I looking for a clarification regarding the pointers. I have compiled the following code in bordland c++ 5.5.1 without any errors. But while i am trying to execute gives a core error.
int main ()
{
int x=10,y=20;
int &a=x;
int &b=y;
int *c;
int *d;
*c=x;
*d=y;
return 0;
}
Basicall... | The code you posted is C++, not C. And your problem is that you need to make those pointers actually point at something:
int * c = & x; // make c point at x
* c = 42; // changes x
|
1,299,272 | 1,299,747 | Difference between code generated using a template function and a normal function | I have a vector containing large number of elements. Now I want to write a small function which counts the number of even or odd elements in the vector. Since performance is a major concern I don't want to put an if statement inside the loop. So I wrote two small functions like:
long long countOdd(const std::vector<int... | Your template version will generate code like this:
template <>
long long countTemplate<true>(const std::vector<int>& v1)
{
long long count = 0;
const int size = v1.size();
for(int i = 0; i < size; ++i)
{
if(true)
{
if(v1[i] & 1)
{
... |
1,299,422 | 1,299,449 | How do I port code that contains #pragma optimize( "a" ) from VC++7 to VC++9? | I'm moving my C++ codebase from Visual Studio 2k3 to Visual Studio 2k8. Code contains
#pragma optimize( "a", on )
MSDN says that it means "assume no aliasing". Later versions of VS refuse to compile this and MSDN doesn't seem to say what to do with code containing this #pragma.
What does "assume no aliasing" mean and ... | Aliasing is when you have stuff like this:
int a[100];
int * p1 = &a[50];
int * p2 = &a[52];
Now a, p1 and p2 are all aliases for the array, or parts of it. This situation can prevent the compiler from producing optimal array access code (FORTRAN forbids it, which is why it is so good with array performance).
The pr... |
1,299,691 | 1,299,810 | When does the C++ default assignment operator become unaccessible? | If I define an own assignment operator, which has a different signature than the normally generated default assignment operator:
struct B;
struct A {
void operator = (const B& b) {
// assign something
}
};
does the default assignment operator, in this case operator = (A&) (or the like, correct me if wrong) become ... | No. 12.8/9 says that the assignment operator for class X must be non-static, non-template with a parameter of type X, X&, X const&, X volatile& or X const volatile&. And there is a note which emphasizes that the instantiation of a template doesn't suppress the implicit declaration.
|
1,300,122 | 1,302,300 | Marshalling BSTRs from C++ to C# with COM interop | I have an out-of-process COM server written in C++, which is called by some C# client code. A method on one of the server's interfaces returns a large BSTR to the client, and I suspect that this is causing a memory leak. The code works, but I am looking for help with marshalling-out BSTRs.
Simplifying a bit, the IDL fo... | anelson has covered this pretty well, but I wanted to add a couple of points;
CoTaskMemAlloc is not the only COM-friendly allocator -- BSTRs are recognized by the default marshaller, and will be freed/re-allocated using SysAllocString & friends.
Avoiding USES_CONVERSION (due to stack overflow risks -- see anelson's an... |
1,300,180 | 1,300,240 | Ignore OpenMP on machine that does not have it | I have a C++ program using OpenMP, which will run on several machines that may have or not have OpenMP installed.
How could I make my program know if a machine has no OpenMP and ignore those #include <omp.h>, OpenMP directives (like #pragma omp parallel ...) and/or library functions (like tid = omp_get_thread_num();) ... | OpenMP is a compiler runtime thing and not a platform thing.
ie. If you compile your app using Visual Studio 2005 or higher, then you always have OpenMP available as the runtime supports it. (and if the end-user doesn't have the Visual Studio C runtime installed, then your app won't work at all).
So, you don't need to ... |
1,300,327 | 1,300,346 | Sort function does not work with function object created on stack? | #include<iostream>
#include<vector>
#include<algorithm>
class Integer
{
public:
int m;
Integer(int a):m(a){};
};
class CompareParts
{
public:
bool operator()(const Integer & p1,const Integer & p2)
{
return p1.m<p2.m;
}
}obj1;
int main()
{
s... | Integer obj2() isn't the definition of an object, it is the declaration of a function named obj2 returning an Integer (put it outside any function to understand why it is so). This occurs also sometimes with more complex constructions where it can be even more confusing. Some name this the most vexing parse.
Here is t... |
1,300,565 | 1,300,991 | How should I compare a c++ metaprogram with an C code ? (runtime ) | I have ported a C program to a C++ Template Meta program .Now i want to compare the runtime .
Since there is almost no runtime in the C++ program , how should i compare these 2 programs.
Can i compare C runtime with C++ compile time ? or is it just not comparable ?
| You can compare anything you want to compare. There is no one true rule of what should be compared.
You can compare the time each version takes to execute, or you can compare the time taken to compile each.
Or you can compare the length of the program, or the number of 'r' characters in the source file.
You could compa... |
1,300,623 | 2,342,681 | Can someone provide an example of seeking, reading, and writing a >4GB file using boost iostreams | I have read that boost iostreams supposedly supports 64 bit access to large files semi-portable way. Their FAQ mentions 64 bit offset functions, but there is no examples on how to use them. Has anyone used this library for handling large files? A simple example of opening two files, seeking to their middles, and cop... | Short answer
Just include
#include <boost/iostreams/seek.hpp>
and use the seek function as in
boost::iostreams::seek(device, offset, whence);
where
device is a file, stream, streambuf or any object convertible to seekable;
offset is a 64-bit offset of type stream_offset;
whence is BOOST_IOS::beg, BOOST_IOS::cur or B... |
1,300,718 | 1,300,903 | C++ .NET convert System::String to std::string | How do you convert System::String to std::string in C++ .NET?
| There is cleaner syntax if you're using a recent version of .net
#include "stdafx.h"
#include <string>
#include <msclr\marshal_cppstd.h>
using namespace System;
int main(array<System::String ^> ^args)
{
System::String^ managedString = "test";
msclr::interop::marshal_context context;
std::string standard... |
1,300,769 | 1,300,798 | Threads in C, C++, C++0x, pthread and boost | A question about threads in C/C++...
C++0x syntax
#include <thread>
void dummy() {}
int main(int, char*[]) {
std::thread x(dummy);
std::thread y(dummy);
...
return 0;
}
How many threads are there? Two (x and y) or three (x, y and main)? Can I call this_thread::yield() in main? And what do I get from call... | In each case you have created two additional threads so you have three (x, y, and main). You'll get a different id on each of the threads including a call in main.
|
1,300,778 | 1,300,820 | How to prevent the linker from optimizing away startup code? | I have the following problem: My (C++-)project consists of several subprojects. In each, I have several files with code I want to run at startup. My solution so far is to use static variables which call the respective code on initialization like this:
// Foo.cpp
static TFooRegistry sFooRegistry; // does stuff in con... | There are no standard conformant ways of forcing objects in libraries to be initialised - you have to use tricks depending on your particular platform(s). The difference between a DLL and and a static library (on Windows, at least) is that the
former has start-up and shut-down code that is executed by the OS, whereas ... |
1,301,051 | 1,301,061 | Map pointers to immutable objects with Hashtable in .NET | I have a Hashtable object which "names" or "map" various fields in a class with a string
ref class Interrupt{
Interrupt(){
this->type = 0;
this->size = 0;
}
int type;
int size;
}
Interrupt^ interrupt = gcnew Interrupt();
Hashtable^ map = gcnew Hashtable();
map->Add("InterruptType", interrupt->type);
... |
I understand that it is because they are immutable.
You understand wrong. Yes, integers are immutable. But the map values didn't change because integers are value types, and so were passed to the map's Add() method by value. In other words, the map holds a copy of the value passed to the Add() method rather than a... |
1,301,056 | 1,301,202 | Looking for the most elegant code dispatcher | I think the problem is pretty common. You have some input string, and have to call a function depending on the content of the string. Something like a switch() for strings.
Think of command line options.
Currently I am using:
using std::string;
void Myclass::dispatch(string cmd, string args) {
if (cmd == "foo")
... | The ugly macro solution, which you kind-of asked for. Note that it doesn't automatically register, but it does keep some things synchronized, and also will cause compile errors if you only add to mappings, and not the function in the source file.
Mappings.h:
// Note: no fileguard
// The first is the text string of th... |
1,301,099 | 1,301,123 | VC++ LNK2001: unresolved external symbol only when compiling on 64bit | I have made a dll that compiles fine in 32bit mode, but when compiling in 64bit mode (both on a 32bit box cross compiling and on a native 64bit box) I get the above error.
The symbol that it is complaining about are the following:
"struct return_info_ * __cdecl patch_file(char *,char *,char *)"
I am new to C++ but I t... | The declaration in the header looks correct, but for some reason, in your 64bit build, the actual implementation not being found.
Is this defined in your library? It may not have been compiled correctly in its 64bit version.
If this is a function that's part of your application, make sure the correct source file is ... |
1,301,277 | 1,301,343 | C++ Boost: what's the cause of this warning? | I have a simple C++ with Boost like this:
#include <boost/algorithm/string.hpp>
int main()
{
std::string latlonStr = "hello,ergr()()rg(rg)";
boost::find_format_all(latlonStr,boost::token_finder(boost::is_any_of("(,)")),boost::const_formatter(" "));
This works fine; it replaces every occurrence of ( ) , with a " "... | It is nothing to worry about. In the last few releases of MSVC, they've gone into full security-paranoia mode. std::copy issues this warning when it is used with raw pointers, because when used incorrectly, it can result in buffer overflows.
Their iterator implementation performs bounds checking to ensure this doesn't ... |
1,301,380 | 1,301,465 | g++ "is not a type" error | Writing a templated function, I declared:
template <typename T>
T invertible(T const& container, T::size_type startIndex, T::size_type endIndex);
Compiling with g++ 4.0.1 I got the error:
error: 'T::size_type' is not a type
| As you found out T::size_type needs to be prefixed with typename.
Why?
From "C++ Templates: The Complete Guide"
The language definition resolves this problem by specifying that in general a dependent qualified name does not denote a type unless that name is prefixed with the keyword typename.
... The typename prefix ... |
1,301,543 | 1,301,579 | Unresolved External (abstract class constructor/destructor) | So, I have an abstract class Panel and an implementation of it MyPanel. They look similar to this:
class Panel : public QWidget
{
public:
Panel(QWidget* parent = 0) = 0;
virtual ~Panel() = 0;
// but wait, there's more!!
};
class MyPanel : public Panel
{
public:
MyPanel(QWidget* parent = 0);
~MyPanel() {}; //... |
there is no such thing like virtual constructor.
You still should provide implementation of destructor.
|
1,301,736 | 1,301,785 | Can you rewrite this snippet without goto | Guys, I have the following code that is inside a big while loop that iterates over a tree. This is as fast as I can get this routine but I have to use a goto. I am not fundamentally against goto but if I can avoid them I would like to. (I am not trying to start a flame war, please.)
The constraints:
The current=curre... | insideloopy:
cnt++;
if ( current->hasChild() )
{
current = current->child();
goto insideloopy;
}
I love infinite loops.
while (true) {
cnt++;
if (!current->hasChild()) break;
current = current->child();
}
Of course you can do it in many other ways (see other answers). do while, put the check in the w... |
1,301,850 | 1,304,994 | Tools to find included headers which are unused? | I know PC-Lint can tell you about headers which are included but not used. Are there any other tools that can do this, preferably on linux?
We have a large codebase that through the last 15 years has seen plenty of functionality move around, but rarely do the leftover #include directives get removed when functionality... | DISCLAIMER: My day job is working for a company that develops static analysis tools.
I would be surprised if most (if not all) static analysis tools did not have some form of header usage check. You could use this wikipedia page to get a list of available tools and then email the companies to ask them.
Some points you... |
1,301,923 | 1,301,954 | Reading binary files without buffering the whole file into memory in C++ | In order to make a binary comparer I'm trying to read in the binary contents of two files using the CreateFileW function. However, that causes the whole file to be bufferred into memory, and that becomes a problem for large (500MB) files.
I've looked around for other functions that'll let me just buffer part of the ... | You could use memory mapped files to do this. open with createFile, use createFileMapping then MapViewOfFile to get a pointer to the data.
|
1,302,025 | 1,302,294 | Game engine map editor. SDL->wxWidgets | I have been writing an OpenGL game engine for a while which uses SDL for all the window management and for portability. I would like to create a level editor using the full engine. The engine itself isn't at all tied in with SDL except for input. I would like to use wxWidgets for the GUI and I have been looking at some... | In all likelihood it would be easier to use one GUI API per application as opposed to merging the two together (i.e. easier to have SDL/OpenGL in your game and wxWidgets/OpenGL in your level editor). Usually these libraries are not built to be merged together or used in conjunction with other libraries so it would be n... |
1,302,141 | 1,365,223 | How do I create and maintain a code reuse library? | I am trying to setup a repository of reusable code. I was thinking about having each reusable code module have a certain “Maturity Level” rating. The rating would be defined as the level at which a reusable code lies within a certain set of requirements. The highest maturity level will be the highest degree of stand... | Setting up a code reuse repository is a difficult task. The main difficulty is not in how you set it up but in how you communicate the existence of the various libraries in the repository. Reuse libraries only good if they are used, and they are only used if they are known, and they are only used widely if the quality ... |
1,302,237 | 1,341,795 | Marshalling CodeElements to an IntPtr in C# | I am writing a Visual Studio add in and need to marshall a managed CodeElements object to it's unmananged form. I just need the pointer in memory, as I can cast it and treat it like a CodeElement on the unmanaged side.
[DllImport("CodeMethodsToString.dll")]
private static extern BSTR* CodeMethodsToString(void*... | Looks like Jonathan was close. This is how I'd do it:
[DllImport("CodeMethodsToString.dll")]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string CodeMethodsToString(IntPtr functionObject);
public static void CodeMethodsToXML(XmlElement parent, CodeElements elements)
{
GCHandle pin;
try
{
... |
1,302,347 | 1,302,408 | Tree iterator, can you optimize this any further? | As a follow up to my original question about a small piece of this code I decided to ask a follow up to see if you can do better then what we came up with so far.
The code below iterates over a binary tree (left/right = child/next ). I do believe there is room for one less conditional in here (the down boolean). The fa... | Why not a recursive solution?
void processTree (const BaseNodePtr ¤t, unsigned int & cnt )
{
cnt++;
if (current->hasChild())
processTree(current->child());
if (current->hasNext())
processTree(current->next());
}
Since shared_ptr seems to be your bottleneck, why not improve it? Are you using thread... |
1,302,368 | 1,304,109 | How to tell if OpenMP works in my C++ program | I am using OpenMP to do multithreading with my nested loops. Since new to this stuff, I am not sure if I am using OpenMP in the correct way so that it can actually do the parallel programming. So I like to know if I can measure the performance of my C++ program that uses OpenMP so I can tell it actually works and I am ... | #include <omp.h>
...
int target_thread_num = 4;
omp_set_num_threads(target_thread_num);
unsigned long times[target_thread_num];
// Initialize all the times
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
times[thread_id] = start_time();
std::cout << "Thread number: " << omp_get_thread_num() << ... |
1,302,628 | 1,302,690 | Tokyo Cabinet and variable size C++ objects | I'm building a system, with C++, that uses Tokyo Cabinet (original API in C). The problem is I want to store a class such as:
class Entity {
public:
string entityName;
short type;
vector<another_struct> x;
vector<another_struct> y
vector<string> z;
};
The problem i... | You cannot portably treat a non-POD C++ struct/class as a raw sequence of bytes - this is regardless of use of pointers or std::string and std::vector, though the latter virtually guarantee that it will break in practice. You need to serialize the object into a sequence of chars first - I'd suggest Boost.Serialization ... |
1,302,785 | 1,302,877 | "unresolved external symbol" for unreferenced function | I'm in Visual Studio 2003. I have a function in a very common module which requires 3 other modules. I want only projects using the new function to have to include the 3 other modules, and those that don't reference the function to link without "unresolved external symbol" errors. I tried function level linking, OPT... |
I have a function in a very common module which requires 3 other modules. I want only projects using the new function to have to include the 3 other modules, and those that don't reference the function to link without "unresolved external symbol" errors.
It sounds to me that you should be separating this new function... |
1,302,786 | 1,304,588 | C++ IDE for Solaris SPARC | We've been given a C++ code base that was apparently developed using Rational Apex as the front end. In our opinion, Apex is less than ideal for C++ development.
We're looking for an IDE we can use that has syntax highlighting, code-walking (go to definition, show usages), and isn't a pain to use.
We've looked at NetBe... | Last time I was working on a Solaris codebase, I used Visual Studio. Yes, the Microsoft product. Modern versions of Both Visual Studio and Sun Studio are fairly standards compliant. As a result, I could debug application logic on Windows. For the low-level stuff we relied on Qt. As a bonus, once you've got the port to ... |
1,302,974 | 1,303,002 | How can I read from an std::istream (using operator>>)? | How can I read from an std::istream using operator>>?
I tried the following:
void foo(const std::istream& in) {
std::string tmp;
while(in >> tmp) {
std::cout << tmp;
}
}
But it gives an error:
error: no match for 'operator>>' in 'in >> tmp'
| Operator >> modifies stream, so don't pass by const, just a reference.
|
1,303,051 | 1,303,111 | Has the STL changed much? | I'm wanting to become conversant in the use of the Standard Template Library. If I come across a general reference or beginner's guide published around 1995-97, can I rely on the information in it? How much has STL changed in the last dozen years?
| Yes! There are new additions. The TR1 update is now implemented in most environments.
Your older book is still useful to learn the basics. But you will want to find a reference for TR1 to learn about some very useful new features. In a couple of areas, the new features are preferred over older ones. (What comes ... |
1,303,123 | 1,303,130 | What is a handle in C++? | I have been told that a handle is sort of a pointer, but not, and that it allows you to keep a reference to an object, rather than the object itself. What is a more elaborate explanation?
| A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't g... |
1,303,890 | 1,303,910 | derive problem about c++ | Why I can't access base class A's a member in class B initialization list?
class A
{
public:
explicit A(int a1):a(a1)
{
}
explicit A()
{
}
public:
int a;
public:
virtual int GetA()
{
return a;
}
};
... | A's constructor runs before B's, and, implicitly or explicitly, the former construct all of A's instance, including the a member. Therefore B cannot use a constructor on a, because that field is already constructed. The notation you're trying to use indicates exactly to use a constructor on a, and at that point it's ju... |
1,303,899 | 1,303,915 | Performance difference between ++iterator and iterator++? | My workmate claims that for object types preincrement is more efficient than post increment
e.g.
std::vector<std::string> vec;
... insert a whole bunch of strings into vec ...
// iterate over and do stuff with vec. Is this more efficient than the next
// loop?
std::vector<std::string>::iterator it;
for (it = vec.be... | Postincrement must return the value the iterator had BEFORE it was incrementing; so, that previous value needs to be copied somewhere before altering it with the increment proper, so it's available to return. The extra work may be a little or a lot, but it certainly can't be less than zero, compared to a preincrement, ... |
1,303,947 | 1,303,966 | C++ compiler warning - returning local variable | I'm simply trying to overload a + operator and I'm getting this compiler warning
reference to local variable 'tmp' returned
Here is the code for the overload
const Int& Int::operator+(const Int& p) const
{
Int tmp = value + p.value;
return tmp;
}
Here is the class
class Int{
int value;
public:
Int() {... | You can't return a reference to a local variable. Inside the operator+() function, you're creating a local variable called tmp. It will get destroyed as soon as the function exits. You can't return a reference to that variable, because it no longer exists when the calling function gets the return value.
Change your def... |
1,303,993 | 1,304,166 | Pre-allocate space for C++ STL queue | I'm writing a radix sort algorithm using queues and I would like to have a STL queue allocate space before I start adding things to the queue so that I can avoid constant dynamic resizing operations.
Even though this doesn't exist, I want something with the effect of...
queue<int> qs(N);
for(int i=0;i<N;++i)
qs.push... | Chances are this is not a problem. Deque's allocate in chunks anyway, so you'll probably only reallocate a few times. Have you determined this to be a bottleneck?
Anyway, the standard does not give an accessor to the `queue''s container, because that would defeat the purpose of encapsulation.
If you're really worried, ... |
1,304,035 | 1,304,092 | Access member function of another .cpp within same source file? | I am working in Visual C++. I have two .cpp files in the same source file. How can I access another class (.cpp) function in this main .cpp?
| You should define your class in a .h file, and implement it in a .cpp file. Then, include your .h file wherever you want to use your class.
For example
file use_me.h
#include <iostream>
class Use_me{
public: void echo(char c);
};
file use_me.cpp
#include "use_me.h" //use_me.h must be placed in the same directory ... |
1,304,040 | 1,304,071 | C++ Constant Expression and Array Bounds | Can someone please explain (what might be my perceived) disparity in errors in the following code? Essentially why are "//OK" okay and "//error" errors?
(Compiler is i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490))
#include <cmath>
#include <iosfwd>
template <typename T>
class TT{
char _c[sizeof(T)... | The problem is in where the arrays are declared.
You can's declare an array with non-constant size at file level since the compiler needs to know at compile time how much to allocate and in your case this would require a function call.
When you do the same at function level the C++ extension your compiler supports kick... |
1,304,174 | 1,304,186 | How to strip debug code during compile time in C++? | Say I have a C++ function debugPrint(int foo). How can I most conveniently strip that from release builds? I do not want to surround every call to debugPrint with #ifdefs as it would be really time consuming. On the other hand, I want to be 100% sure that the compiler strips all the calls to that function, and the func... | Use conditinal compilation and a macro:
#ifdef _DEBUG
#define LOG( x ) debugPrint( x )
#else
#define LOG( x )
#endif
Define _DEBUG for the debug build and not define it for the release build. Now in release build every
LOG( blahbhahblah );
will be expanded into an empty string - even the parameters will not be ... |
1,304,187 | 1,304,482 | How to convert a vector<pair<int,int> > to multimap<int,int> efficiently? | How to convert a multimap<int,int> to vector<pair<int,int> > efficiently
EDIT:
Sorry for the trouble I was actually looking for converting vector to map
| The value type of a multimap<int,int> is pair<int,int> - exactly what you would like your vector to hold. So, you can use the constructor to initialize the vector from the multimap:
std::vector< std::pair<int,int> > v( mmap.begin(), mmap.end() );
Or, if you have an existing vector where you want to copy the elements:
... |
1,304,680 | 1,304,785 | Object slicing with private copy constructor in derived class in C++ | Suppose I have something like the following in test.cxx (and that I do the object slicing at 1 intentionally):
class A {
};
class B : public A {
// prevent copy construction and assignment
B(const B& other);
B& operator=(const B& other);
public:
explicit B(){}
};
class C {
A m_a;
public:
explicit C() : m_... | I dare to disagree with Comeau in this case. In fact, the following code fails to compile as expected, because binding an rvalue to a const reference requires accessible copy constructor.
class A {
};
class B : public A {
B(const B& other);
B& operator=(const B& other);
public:
explicit B(){}
};
int main()
{
... |
1,304,723 | 1,304,901 | template function specialization problem | I am using templates to implement a range checked conversion from int to enum. It looks like this:
template<typename E>
E enum_cast(const int &source);
The template function placed more or less in the root-directoy of the project. When defining a new enum that is foreseen to be assigned values from a config file like ... | The explicit specializations have to be visible everywhere they are used. And as they are definitions, they can't be repeated in every compilation unit. So in the header file where you define an enum you want to check you say
#include "enum_cast.h"
enum Foo { Foo_A, Foo_B, Foo_C };
template<> Foo enum_cast<Foo>(int s... |
1,304,736 | 1,304,831 | reinterpret_cast to void* not working with function pointers | I want to reinterpret cast a function pointer into a void* variable. The type of the function pointer will be of type Class* (*)(void*).
Below is the sample code,
class Test
{
int a;
};
int main()
{
Test* *p(void **a);
void *f=reinterpret_cast<void*>(p);
}
The above code works well with Visual Studio... | reinterpret_cast can't be used to cast a pointer to function to a void*. While there are a few additional things that a C cast can do which aren't allowed by combination of static, reinterpret and const casts, that conversion is not one of them.
In C the cast is allowed, but it's behavior isn't defined (i.e. even roun... |
1,304,737 | 1,304,752 | How is *array* memory allocated and freed in C and C++? | My question specifically is in regards to arrays, not objects.
There a few questions on SO about malloc()/free() versus new/delete, but all of them focus on the differences in how they are used. I understand how they are used, but I don't understand what underlying differences cause the differences in usage.
I often h... | There's no real difference under the hood - usually the default new and delete operators will simply call through to malloc and free.
As for "the stigma of being more expensive", my theory is this: back in the day, every cycle counted, and the time taken by malloc really was significant in many situations. But by the ... |
1,304,771 | 1,304,804 | C and C++: Freeing PART of an allocated pointer | Let's say I have a pointer allocated to hold 4096 bytes. How would one deallocate the last 1024 bytes in C? What about in C++? What if, instead, I wanted to deallocate the first 1024 bytes, and keep the rest (in both languages)? What about deallocating from the middle (it seems to me that this would require splitti... | If you have n bytes of mallocated memory, you can realloc m bytes (where m < n) and thus throw away the last n-m bytes.
To throw away from the beginning, you can malloc a new, smaller buffer and memcpy the bytes you want and then free the original.
The latter option is also available using C++ new and delete. It can al... |
1,304,847 | 1,304,956 | Is it possible to lower the privilege level when calling CoCreateInstance on Vista? | Okay, I have a plugin for IE that when installed needs to (with the user's permission) restart IE.
To do this I have a DLL that is invoked by the installer. And it works, but the problem is that when IE is restarted on Vista, it is restarted with the administrator privileges of the installer, which is a problem for a n... | Okay, I found the solution from here:
http://social.msdn.microsoft.com/Forums/cs-CZ/ieextensiondevelopment/thread/78a2bc18-1920-4e58-af7e-48dbcebe7643
From my installer DLL I need to launch a new thread, and impersonate the current user on that thread, and then set a low integrity level, and create the COM instance wit... |
1,305,055 | 1,305,152 | Reference initialization in C++ | Greetings, everyone!
Examining my own code, I came up to this interesting line:
const CString &refStr = ( CheckCondition() ) ? _T("foo") : _T("bar");
Now I am completely at a loss, and cannot understand why it is legal. As far as I understand, const reference must be initialized, either with r-value or l-value. Uninit... | Simpler example: const int x = foo();
This constant too has to be initialized, and for that foo() needs to be called. That happens in the order necessary: x comes into existance only when foo returns.
To answer your additional questions: If foo() would throw, the exception will be caught by a catch() somewhere. The try... |
1,305,132 | 1,305,149 | crash when calling library | Let's hope I can dumb this down without leaving out crucial details...
I've got a test program:
#include <lib.h>
const char * INPUT = "xyz";
int main()
{
initializeLib();
LibProcess * process = createLibProcess();
fprintf( stderr, "Before run(%s)\n", INPUT );
process->run(INPUT);
fprintf( stderr,... | Is process definitely set to a non-NULL valid pointer before it is dereferenced to call run?
|
1,305,422 | 1,305,470 | How to make a string preprocessor definition from command-line in VC 2005 (C++)? | The documentation tells me that /D command-line switch can be used to do this, like so:
CL /DDEBUG TEST.C
would define a DEBUG symbol, and
CL /DDEBUG=2 TEST.C
would give it the value 2.
But what do I do if I would like to get the equivalent of a string define, such as
#define DEBUG "abc"
?
| Due to the way command line is parsed in Windows, you'll have to escape the quotes.
CL /DDEBUG=\"abc\" TEST.C
|
1,305,493 | 1,306,713 | Debug DLL's under Windows with GDB | I have some project consisting of a couple of DLL's which have been compiled with MinGW with debug information, and another project with EXE target which uses these DLLs (compiled with MinGW too).
The problem is, I need to put breakpoints on functions inside those DLLs, but GDB, although sets them, just silently ignor... | Make sure you are compiling with gcc optimization level flag setted to 0 ( -O0 ).
|
1,305,502 | 1,368,792 | Designing efficient C++ code for fibers | How do I utilize fibers best in my game code? Should it only be used to manage nonpreemptive context-switches while loading resources (i.e. files from disk)? Or do I allow all types of game entities to run in a fiber? How do I schedule?
C++ or pseudo code samples greatly appreciated!
| Don't? It's like a thread only with very little CRT support (unlike threads) and some hidden memory requirements like stack and registers.
It may make non-system code easier to write but it complicates to an unjustifiable degree.
|
1,305,713 | 1,305,725 | How do ensure that while writing C++ code itself it will not cause any memory leaks? | Running valgrind or purify would be the next steps
But while while writing the code itself how do you ensure that it will not cause any memory leaks?
You can ensure following things:-
1: Number of new equal to delete
2: Opened File descriptor is closed or not
Is there any thing else?
| Use the RAII idiom everywhere you can
Use smart pointers, e.g. std::auto_ptr where appropriate. (don't use auto_prt in any of the standard collections as it won't work as you think it will)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.