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 |
|---|---|---|---|---|
615,100 | 615,128 | Should I learn Python after C++? | I`m currently studying C++ and want to learn another language.
For work I use C# + ASP (just started learning it, actually), but I want something "less Microsoft" and powerful.
I have heard Python is a popular and powerful language, not so complicated as C++. But many people mentioned it was hard for them to get back t... | There's no right or wrong answer, really. But I think you'll benefit more from learning Python. Given the similarities between C# and C++, you'll learn a different way of thinking from Python. The more ways you learn to think about a problem, the better it makes you as a programmer, regardless of the language.
|
615,264 | 616,538 | C++ Parallelization Libraries: OpenMP vs. Thread Building Blocks | I'm going to retrofit my custom graphics engine so that it takes advantage of multicore CPUs. More exactly, I am looking for a library to parallelize loops.
It seems to me that both OpenMP and Intel's Thread Building Blocks are very well suited for the job. Also, both are supported by Visual Studio's C++ compiler and ... | I haven't used TBB extensively, but my impression is that they complement each other more than competing. TBB provides threadsafe containers and some parallel algorithms, whereas OpenMP is more of a way to parallelise existing code.
Personally I've found OpenMP very easy to drop into existing code where you have a para... |
615,355 | 615,366 | Is there any reason to check for a NULL pointer before deleting? | I often see legacy code checking for NULL before deleting a pointer, similar to,
if (NULL != pSomeObject)
{
delete pSomeObject;
pSomeObject = NULL;
}
Is there any reason to checking for a NULL pointer before deleting it? What is the reason for setting the pointer to NULL afterwards?
| It's perfectly "safe" to delete a null pointer; it effectively amounts to a no-op.
The reason you might want to check for null before you delete is that trying to delete a null pointer could indicate a bug in your program.
Edit
NOTE: if you overload the delete operator, it may no longer be "safe" to delete NULL
|
615,523 | 615,584 | Is it OK to pass parameters to a Factory method? | One of the ways to implement Dependency Injection correctly is to separate object creation from business logic. Typically, this involves using a Factory for object creation.
Up until this point, I've never seriously considered using a Factory so I apologize if this question seems a little simplistic:
In all the exampl... | I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.
However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is pra... |
615,551 | 615,555 | How to get width and height from CreateWindowEx() window? C++ | I have made a window with CreateWindowEx() function, now how do i get the width and height from that window i created? This sounds very basic thing to do, but i just couldnt find any answer ;_;
This is needed because the window height is created automatically depending on how the Windows wants to create it.
Language C... | Use GetWindowRect. Subtract the right from the left to get the width and the bottom from the top to get the height.
RECT rect;
if(GetWindowRect(hwnd, &rect))
{
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
}
As a side note, if you'd like the client area instead of the entire window. Yo... |
615,701 | 615,711 | InterlockedIncrement usage | While reading about the function InterlockedIncrement I saw the remark that the variable passed must be aligned on a 32-bit boundary. Normally I have seen the code which uses the InterlockedIncrement like this:
class A
{
public:
A();
void f();
private:
volatile long m_count;
};
A::A() : m_count(0)
{
}
void... | It depends on your compiler settings. However, by default, anything eight bytes and under will be aligned on a natural boundary. Thus an "int" we be aligned on a 32-bit boundary.
Also, the "#pragma pack" directive can be used to change alignment inside a compile unit.
I would like to add that the answer assumes Micro... |
615,969 | 631,356 | How to get the running version of Power Point using C++ unmanaged? | I am using C++ unmanaged with Power Point (2003 and 2007).
How do I get the running version of Power Point (2003 or 2007) with IDispatch?
Thanks, any help would be awesome.
| I am sorry I was working in another project. I found a simple way to get the version using CComDispatchDriver instance.
CComVariant ccVersion;
//disp is CComDispatchDrive type
disp.GetPropertyByName("Version", ccVersion);
doing that I get ccVersion = "11.0" for 2003 and "12.0" for 2007.
To cast it to string I used CS... |
615,993 | 616,025 | Parsing a string in C++ | I have a huge set of log lines and I need to parse each line (so efficiency
is very important).
Each log line is of the form
cust_name time_start time_end (IP or URL )*
So ip address, time, time and a possibly empty list of ip addresses or urls separated by semicolons. If there is only ip or url in the last list ther... | Maybe Boost RegExp lib will help you.
http://www.boost.org/doc/libs/1_38_0/libs/regex/doc/html/index.html
|
616,573 | 616,703 | Isn't the Factory pattern the same thing as global state? | Let's say I have a class like this:
class MonkeyFish
{
MonkeyFish( GlobalObjectA & a, GlobalObjectB & b, GlobalObjectC & c);
private:
GlobalObjectA & m_a;
GlobalObjectB & m_b;
GlobalObjectC & m_c;
}
Without a factory, I need to do the following in order to instantiated a MonkeyFish.
GlobalObjec... | Are you confusing concepts here?
The Factory pattern is usually applied when you are returning an instance of a concrete class that hides behind an abstract interface. The idea is that the caller will see just the interface and doesn't even have to know what the concrete type of the object is. It is all about creating ... |
616,653 | 616,695 | Portable C++ Stack Trace on Exception | I am writing a library that I would like to be portable. Thus, it should not depend on glibc or Microsoft extensions or anything else that is not in the standard. I have a nice hierarchy of classes derived from std::exception that I use to handle errors in logic and input. Knowing that a particular type of exception... | I think this is a really bad idea.
Portability is a very worthy goal, but not when it results in a solution that is intrusive, performance-sapping, and an inferior implementation.
Every platform (Windows/Linux/PS2/iPhone/etc) I've worked on has offered a way to walk the stack when an exception occurs and match addresse... |
616,936 | 633,337 | How to get Last Active Cell in Excel 2007 | I am working with C++ unmanaged and Excel 2007. I am using a call to the Excel4 API to get the range of cells selected by the user.
When the user selects what I call a "common" range, this call returns a range like this "R1C1:R4C3", which is exactly the format that I need for doing other operations in my application.
H... | The Excel 4 API? Really?
There's a command xlcSelectEnd which you can use to jump to the last cell with text entered in it in any direction from a given cell.
|
617,185 | 617,560 | Approximating a shape boundary using Fourier descriptors | I am trying to approximate shape boundaries by using Fourier descriptors. I know this can be done because I've learned about it in class and read about it in several sources.
To obtain the Fourier descriptors of a boundary of (x,y) coordinates, I do the following:
1) Turn (x,y) coordinates into complex numbers of the f... | The result you are getting is what would be expected if you threw out the low frequencies instead of the high ones. Are you sure about which frequencies are which?
|
617,248 | 617,261 | Can the HWND from CreateWindow/CreateDialog be GetMessage'd from another thread? | Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?
Are HWNDs tied to threads?
Trying the contrived example below I never see GetMessage() fire.
HWND g_hWnd;
DWORD WINAPI myThreadProc(LPVOID lpParam)
{
while(GetMessage(&msg, hWnd, 0, 0) >... | No.
GetMessage returns messages on the current thread's input queue. The HWND parameter is a filter, so that GetMessage only returns messages in the current thread's input queue intended for that window.
Windows have thread affinity - messages intended for a window get handled on the thread that created and therefore ... |
617,358 | 617,364 | Get optarg as a C++ string object | I am using getopt_long to process command line arguments in a C++ application. The examples all show something like printf("Username: %s\n", optarg) in the processing examples. This is great for showing an example, but I want to be able to actually store the values for use later. Much of the rest of the code uses strin... | You told printf that you were suppling a c style string (null terminated array of chars) when specifying %s, but you provided a string class instead. Assuming you are using std::string try:
printf("bar : %s\n", bar.c_str());
|
617,513 | 617,518 | How to identify if an object should be on the stack or not? | I was looking for a rule of thumb for allocating objects on stack or heap in C++. I have found many discussions here on SO. Many people said, it's about the lifetime of an object. If you need more lifetime than the scope of the function, put it in the heap. That makes perfect sense.
But what made me confusing is, many... | Well firstly vectors (and all the STL container classes) always allocate from the heap so you don't have to worry about that. For any container with a variable size it's pretty much impossible to use the stack.
If you think about how stack allocation works (at compile time, basically by incrementing a pointer for each ... |
617,555 | 617,696 | Error with two ways of linking boost regex | I understand that boost regex static library is created with the ar utility by archiving the individual object files.
I linked boost regex library by using the -l option in gcc. This worked very well.
g++ *.o libboost_regex-gcc-1_37.a -o sairay.out
I individually compiled the boost regex source files and then tried to... | I think it's supposed to be:
g++ *.o -L. -lboost_regex-gcc -o sairay.out -static
|
617,571 | 617,586 | Microsoft _s functions, are they part of the C++ standard now? | I just recently changed my IDE to MS Visual Studio 2005 coming from MSVC++ 6, and I've gotten a lot of deprecation warnings. Rather than ignore the warning, I started to change them to the _s equivalents. However, I then found out that these were microsoft-only implementations.
I read somewhere that they were pushing... | The *_s() functions are not part of the C standard, but there is a pending 'Technical Report' proposing that they be added (I'm not sure if the routines in the TR are exactly the same as Microsoft's or if they're just similar).
TR 24731-1: Extensions to the C Library Part I: Bounds-checking interfaces:
http://www.ope... |
617,726 | 617,783 | How to get debug information for an abstract(?) pimpl in C++? | I have a wrapper class that delegates its work to a pimpl, and the pimpl is a pointer to a baseclass/interface with no data that is specialized in several different ways.
Like this:
class Base
{
void doStuff=0;
};
class Derived
{
int x,y;
void doStuff()
{
x = (x+y*2)*x; //whatever
}
};
cla... | Just keep expanding out the tree in the Autos window or one of the Watch windows:
alt text http://www.freeimagehosting.net/uploads/626b4a37ee.png
|
617,809 | 617,853 | Stack unwinding in case of structured exceptions | This question provides more clarity on the problem described here. I did some more investigation and found that the stack unwinding is not happening in the following piece of code:
class One
{
public:
int x ;
};
class Wrapper
{
public:
Wrapper(CString csText):mcsText(csText)
{
CString csTempText;
... | If you want to use SEH, you must use _set_se_translator function and /EHa compiler option.
|
617,825 | 617,834 | Searching for Junk Characters in a String | Friends
I want to integrate the following code into the main application code. The junk characters that come populated with the o/p string dumps the application
The following code snipette doesnt work..
void stringCheck(char*);
int main()
{
char some_str[] = "Common Application FE LBS Serverr is down";
string... | Your char probably is represented signed. Cast it to unsigned char instead to avoid that it becomes a negative integer when casting to int:
if ((unsigned char)newString[i] >128)
Depending on your needs, isprint might do a better job, checking for a printable character, including space:
if (!isprint((unsigned char)newS... |
617,943 | 617,987 | Best Replacement for a Character Array | we have a data structure
struct MyData
{
int length ;
char package[MAX_SIZE];
};
where MAX_SIZE is a fixed value . Now we want to change it so as to support
"unlimited" package length greater than MAX_SIZE . one of the proposed solution
is to replace the static array with a pointer and then dynamical... | I would also wrap a vector:
// wraps a vector. provides convenience conversion constructors
// and assign functions.
struct bytebuf {
explicit bytebuf(size_t size):c(size) { }
template<size_t size>
bytebuf(char const(&v)[size]) { assign(v); }
template<size_t size>
void assign(char const(&v)[size]... |
618,111 | 618,152 | C++ (Standard) Exceptions and Unicode | I'm running into an issue where I'm processing unicode strings and I want to do some error reporting with standard exceptions. The error messages contained in standard exceptions are not unicode.
Usually that hasn't been a problem for me because I can define the error message in non-unicode and have enough informatio... | I think Peter Dimov's rationale as pointed out in the Boost error handling guidelines covers this well:
Don't worry too much about the what()
message. It's nice to have a message
that a programmer stands a chance of
figuring out, but you're very unlikely
to be able to compose a relevant and
user-comprehensib... |
618,169 | 618,175 | Clean vector every loop iteration. What is the most memory efficient way? | I have a question about the std::vector.
I have a very memory intensive algorithm where I forsee that predicting vector sizes and reserving enough memory for the vectors in advance will help me a lot with reducing memory usage.
Which of the following is better:
for ( ... ) {
std::vector<Type> my_vector;
my_vector.r... | With the first variant you reallocate the vector's buffer on each iteration – that's usually quite costly. With the second variant you only reallocate occasionally. The second variant is better since speed is a priority for you.
It's unclear from you question where the number of elements is know from. Maybe you even ca... |
618,204 | 618,220 | De facto list of primitive types usable in C++ | If, for example, you're going to write a variant type class, you will naturally need identification of what type an instance of that class is carrying. I'm wondering if anyone knows of any official or semi-official (de-facto?) reference of all primitive datatypes one would possibly be interested in?
Only primitives, a... | The only official reference is the ISO/IEC 14882 C++ Standard.
|
618,215 | 72,674,082 | How do I catch system-level exceptions in Linux C++? | The following catch() is not called:
void test(void)
{
int i=1,j=0,k;
try
{
k = i/j;
}
catch(...)
{
...handle it...
}
}
Is there a way to catch this kind of exception?
| below code implement __try/__except effect like in visual studio c++
or
how to simulate __try/__except for gcc or g++
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
__thread jmp_buf * gThreadData; //thread local storage variable declare
void FPE_ExceptionHandler(int signal)
{
printf("exception handler... |
618,472 | 618,580 | using of std::accumulate | Need prettier solution of below example but with std::accumulate.
#include <algorithm>
#include <vector>
#include <iostream>
class Object
{
public:
Object( double a, double b ):
a_( a ),
b_( b )
{}
double GetA() const { return a_; }
double GetB() const { return b_; }
// other metho... | do changes in Calculator and main function.
struct Calculator
{
double operator() ( double result, const Object& obj )
{
return result + ( obj.GetA() * obj.GetB());
}
};
int main()
{
std::vector< Object > collection;
collection.push_back( Object( 1, 2 ) );
collection.push_back( Object(... |
618,581 | 618,597 | Registering each C/C++ source file to create a runtime list of used sources | For a debugging and logging library, I want to be able to find, at runtime, a list of all of the source files that the project has compiled and linked. I assume I'll be including some kind of header in each source file, and the preprocessor __FILE__ macro can give me a character constant for that file, so I just need t... | I wouldn't do that sort of thing right in the code. I would write a tool which parsed the project file (vcproj, makefile or even just scan the project directory for *.c* files) and generated an additional C source file which contained the names of all the source files in some kind of pre-initialized data structure.
I ... |
618,829 | 618,869 | openGL glDrawElements with interleaved buffers | Thus far i have only used glDrawArrays and would like to move over to using an index buffer and indexed triangles. I am drawing a somewhat complicated object with texture coords, normals and vertex coords. All this data is gathered into a single interleaved vertex buffer and drawn using calls similar to ( Assuming all ... | You cannot have different indexes for the different lists. When you specify glArrayElement(3) then OpenGL is going to take the 3rd element of every list.
What you can do is play with the pointer you specify since essentially the place in the list which is eventually accessed is the pointer offset from the start of the ... |
618,859 | 618,874 | How can I make my own C++ compiler understand templates, nested classes, etc. strong features of C++? | It is a university task in my group to write a compiler of C-like language. Of course I am going to implement a small part of our beloved C++.
The exact task is absolutely stupid, and the lecturer told us it need to be self-compilable (should be able to compile itself) - so, he meant not to use libraries such as Boost ... | Stick to doing a C compiler.
Believe me, it's hard enough work building a decent C compiler, especially if its expected to compile itself. Trying to support all the C++ features like nested classes and templates will drive you insane. Perhaps a group could do it, but on your own, I think a C compiler is more than enoug... |
620,137 | 620,402 | Do the parentheses after the type name make a difference with new? | If 'Test' is an ordinary class, is there any difference between:
Test* test = new Test;
and
Test* test = new Test();
| Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.
Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up i... |
620,378 | 620,437 | Why do C++ templates let me circumvent incomplete types (forward declarations)? | I tried three iterations of the following simple program. This is a highly simplified attempt to write a container-and-iterator pair of classes, but I was running into issues with incomplete types (forward declarations). I discovered that this was in fact possible once I templatized everything - but only if I actuall... | The first requires a definition of container since you are doing a copy operation. If you define the constructor of iter after container's definition you'd be okay. So:
struct container;
struct iter {
container &c;
int *p;
iter(container &c);
};
struct container {
int x;
int &value() { return x; }
iter beg... |
620,498 | 620,563 | How to detect PowerPoint 2007 from a C++ addin? | I need to detect if my addin is in PowerPoint 2007 via my C++ addin. The PowerPoint object model exposes Application.Version, which should work, but I do not know enough about how to use this with IDispatch.
How to detect PowerPoint 2007 from a C++ addin?
| Firstly - call IDispatch::GetIDsOfNames and get id for "Version" property.
After that call IDispatch::Invoke which will get Version porperty value by id.
Also, you could generate wrappers with #import directive and use more easy methods for get value of this property.
Maybe this article will help you http://support.mi... |
620,604 | 620,634 | difference between a pointer and reference parameter? | Are these the same:
int foo(bar* p) {
return p->someInt();
}
and
int foo(bar& r) {
return r.someInt();
}
Ignore the null pointer potential. Are these two functions functionally identical no matter if someInt() is virtual or if they are passed a bar or a subclass of bar?
Does this slice anything:
bar& ref = *ptr_t... | C++ references are intentionally not specified in the standard to be implemented using pointers. A reference is more like a "synonym" to a variable than a pointer to it. This semantics opens some possible optimizations for the compiler when it's possible to realize that a pointer would be an overkill in some situations... |
620,745 | 705,474 | C++: Rotating a vector around a certain point | I am trying to rotate a vector around a certain point on the vector(in C++):
1 2 3
4 5 6
7 8 9
rotated around the point (1,1) (which is the "5") 90 degrees would result in:
7 4 1
8 5 2
9 6 3
Right now I am using:
x = (x * cos(90)) - (y * sin(90))
y = (y * cos(90)) + (x * sin(90))
But I don't want it rotated around ... | The answer depends on your coordinate system.
Computer graphics coordinate system, with (0,0) at Top left
If you are using a computer graphics vector implementation where (0,0) is the top left corner and you are rotating around the point (dx, dy), then the rotation calculation, including the translation back into the o... |
620,752 | 620,813 | Compiling C++ program on Windows XP | I have a problem running a simple Hello-world program in C++ on my Windows XP. I have written a post here:
Using the g++ C++ compiler from cygwin
where I stated the problem and I received many helpful replies, which solved some things. However, I still cannot run my hello-world program. Please, have a look at the pos... | It looks like you have somehow got an illegal character in your code. Did you type the code in yourself or copy & paste it? If the latter, the source you copied from may be suspect in some way - type the code into the editor yourself, save it and recompile.
|
620,795 | 620,817 | Function-wide exception handling in c++ - is it a bad style? | There is a try-catch thing about functions, which I think sometimes may be quite useful:
bool function()
try
{
//do something
}
catch(exception_type & t)
{
//do something
}
So the first part of the question: is this style considered bad in general case?
And the concrete example I used this approach in:
We had... | Really the only reason to function-level try blocks is for constructors, otherwise it's a somewhat obscure feature that doesn't buy you that much. It's just as easy to do it this way:
bool readEntity(...)
{
try
{
while(...)
{
if(...)
{
//lot's of code...
}
... |
620,843 | 620,849 | How do I create an array of pointers? | I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it?
What I have now is:
Student * db = new Student[5];
But each element in that array is the student object, not a pointer to the student object.
Thanks.
| Student** db = new Student*[5];
// To allocate it statically:
Student* db[5];
|
620,914 | 620,979 | C++ concept check vs inheritance | What is the relationship between using virtual functions and C++ inheritance mechanisms versus using templates and something like boost concepts?
It seems like there is quite an overlap of what is possible. Namely, it appears to be possible to achieve polymorphic behavior with either approach. So, when does it make sen... | I think of concepts as a kind of meta-interface. They categorize types after their abilities. The next C++ version supplies native concepts. I hadn't understood it until i came across C++1x's concepts and how they allow putting different yet unrelated types together. Imagine you have a Range interface. You can model th... |
621,084 | 621,090 | Comparing string data received from a socket in C | I have a question on sockets. I have this code:
while(bytes = recv(sClient, cClientMessage, 599, 0)){
This puts the message it recives into cClientMessage and the message is always "Message". How I made an if statement like if(cClientMessage == "Message"){//do func}. Now this code will not do the function I want. ... | Try:
if( strcmp( cClientMessage, "Message")) == 0 ) {
// do something
}
Edit, following suggestion from strager:
A better solution, which does not depend on the received data being null terminated is to use memcmp:
if( memcmp( cClientMessage, "Message", strlen( "Message") )) == 0 ) {
// do something
}
|
621,157 | 621,161 | How to restart a sockets program? | I need my server to stay connected to the server. Does anyone know how to do this? Or post links tutorials anything?
Also it says when it restarts 'could not accept client' so how would I clear everything and make it accept it?
| Server code:
For your server side code, do a loop wrapping the accept call. For the accepted socket that is created create a new thread, so that the next accept will be called right away.
On server startup you may also want to use the SO_REUSEADDR flag. That way if you had a crash, or even a fast restart of the prog... |
621,233 | 621,268 | How to intentionally delete a boost::shared_ptr? | I have many boost::shared_ptr<MyClass> objects, and at some point I intentionally want to delete some of them to free some memory. (I know at that point that I will never need the pointed-to MyClass objects anymore.) How can I do that?
I guess you can't just call delete() with the raw pointer that I get with get().
I'... | You just do
ptr.reset();
See the shared_ptr manual. It is equivalent to
shared_ptr<T>().swap(ptr)
You call reset on every smart pointer that should not reference the object anymore. The last such reset (or any other action that causes the reference count drop to zero, actually) will cause the object to be free'ed usi... |
621,255 | 621,308 | Force screen redraw after drawing to screen's DC C++ | I'm creating a Windows Mobile custom SIP and as the user presses or "hovers" over a button on the keyboard I draw it's corresponding selected image (iPhone-esque) to the screen's DC using ::GetDC(NULL). It is developed in Win32 C++.
My problem is that I can never get the screen to repaint itself, erasing the previous... | Rather than drawing to the background DC, why don't you create a temporary window and draw into that? When you destroy the window, the background should get repainted automatically.
I'm just guessing, because I don't know Windows Mobile, but it could be that Windows is caching the last thing that was drawn into the DC ... |
621,262 | 621,296 | How to run a Qt application? | I have been using Qt creator to make applications using the Qt libraries. I can run these applications by just clicking the play button, but I want to learn how to make applications run just by double clicking on a .exe. So how can I do this?
| I'm assuming you are running windows since you mention an .exe file extension. Look in the debug and/or release subdirectories of your project to find the produced binary. You can double-click on it to run the application. However, there are several DLL's that will be required. So, make sure they are in your PATH or co... |
621,535 | 621,537 | What are data breakpoints? | I just came to know that there are data breakpoints. I have worked for the last 5 years in C++ using Visual Studio, and I have never used data breakpoints.
Can someone throw some light on what data breakpoints are, when to use them and how to use them with VS?
As per my understanding we can set a data breakpoint when w... | Definition:
Data breakpoints allow you to break
execution when the value stored at a
specified memory location changes.
From MSDN: How to: Set a Data Breakpoint:
How to Set a Memory Change Breakpoint
From the Debug Menu, choose New Breakpoint and click New Data Breakpoint
—or—
in the Breakpoints window Menu, cli... |
621,542 | 621,548 | Compilers and argument order of evaluation in C++ | Okay, I'm aware that the standard dictates that a C++ implementation may choose in which order arguments of a function are evaluated, but are there any implementations that actually 'take advantage' of this in a scenario where it would actually affect the program?
Classic Example:
int i = 0;
foo(i++, i++);
Note: I'm n... | It depends on the argument type, the called function's calling convention, the archtecture and the compiler. On an x86, the Pascal calling convention evaluates arguments left to right whereas in the C calling convention (__cdecl) it is right to left. Most programs which run on multiple platforms do take into account th... |
621,573 | 621,581 | How new keyword works in c# | There's a class which is compiled into a dll
//HeaderFile.h
//version 1.0
class __declspec(dllexport) A {
int variable;
//member functions omitted for clarity
};
//implementation file omitted for clarity
You build an exe which uses above class from the dll it was compiled into
#include "HeaderFile.h"
int main()... | In COM, your DLL implements an object factory: The DLL creates the object itself in order to avoid such 'syncho' problems. In .NET, the CLR instantiates the object based on type knowledge pulled from the DLL where the type is implemented. In both cases, the problem you mention is avoided.
|
621,616 | 621,648 | C++: What is the size of an object of an empty class? | I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and point to it like any other object. But, how big is such an object?
I used this small program:
#include <iostream>
using namespace std;
class Empty {};
int main()
{
Emp... | Quoting Bjarne Stroustrup's C++ Style and Technique FAQ, the reason the size is non-zero is "To ensure that the addresses of two different objects will be different." And the size can be 1 because alignment doesn't matter here, as there is nothing to actually look at.
|
621,745 | 621,748 | Signaling an error in file streams in C++ | I have got the following sample:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
cout << file << endl; // 0xbffff3e4
file.open("no such file");
cout << file << endl; // 0
cout << (file == NULL) << endl; // 1
cout << file.fail() << endl;... | file is an object - it cannot be null. However, ifstream has an operator void*() overload which returns 0 when the file is in a bad state. When you say (for example):
cout << file << endl;
the compiler converts this to:
cout << file.operator void*() << endl;
This conversion will be used in all sorts of places - basic... |
621,776 | 626,144 | How to reduce CPU usage of a program? | I wrote a multi-threaded program which does some CPU heavy computation with a lot of floating point operations. More specifically, it's a program which compares animation sequences frame by frame. I.e. it compares frame data from animation A with all the frames in animation B, for all frames in animation A. I carry out... | There are some excellent answers here.
I would only add, from the perspective of having done lots of performance tuning, unless each thread has been optimized aggressively, chances are it has lots of room for cycle-reduction.
To make an analogy with a long-distance auto race, there are two ways to try to win:
Make the... |
622,017 | 622,028 | list of public functions/classes with their corresponded header files | I tried to find a place where I can find ready to copy list of all functions and classes available in each stl header file.
Looking through /usr/include/c++ is not so convenient as I expected.
Google very often shows
http://www.cplusplus.com/reference/
which is not so convenient to copy and paste.
Does anyone knows a ... | I'm not sure if I understood correctly, but if you need a reference and a list of functions from the headers, then maybe dinkumware manuals. If you want examples then try this. If you want an absolute and the true reference then go to the ISO standard.
I forgot to mention SGI STL programmers guide...
|
622,019 | 622,907 | How can I get better profiling? | I need to profile a program to see whether any changes need to be made regarding performance. I suspect there is a need, but measuring first is the way to go. This is not that program, but it illustrates the problem I'm having:
#include <stdio.h>
int main (int argc, char** argv)
{
FILE* fp = fopen ("trivial.c", "r"... | There are certain commonly-accepted beliefs in this business, that I would suggest you examine closely.
One is that the best (if not only) way to find performance problems is to measure the time each subroutine takes and count how many times it is called.
That is top-down. It stems from a belief that the forest is more... |
622,048 | 622,068 | Functor class doing work in constructor | I'm using C++ templates to pass in Strategy functors to change my function's behavior. It works fine. The functor I pass is a stateless class with no storage and it just overloads the () operator in the classic functor way.
template <typename Operation> int foo(int a)
{
int b=Operation()(a);
/* use b here, etc */
}
I... |
Any disadvantage?
Ctors do not return any useful value -- cannot be used in chained calls (e.g. foo(bar()).
They can throw.
Design point of view -- ctors are object creation functions, not really meant to be workhorses.
|
622,129 | 622,138 | Error Logging C++ Preprocessor Macros __LINE__, __FUNCTION__ | I trying to incorporate a simple error logging into my existing app, at the moment it reports errors just using cout so I was hoping to keep a similar interface using the << operator. However I want it to log the line and function the error occurred, but I don't want to have to type __LINE__, __FUNCTION__ every time I ... | myLogClass << "Line No: " << __LINE__ ...
With your operator << chaining will not work since it returns a bool.
bool myLogClass::operator << (const char * input)
It is customary to define stream insertion as follows:
std::ostream& myLogClass::operator << (std::ostream& o, const char * input) {
// do something
... |
622,210 | 622,438 | Problem calling a function when it is in a .lib | I have a class with a static method that looks roughly like:
class X {
static float getFloat(MyBase& obj) {
return obj.value(); // MyBase::value() is virtual
}
};
I'm calling it with an instance of MyDerived which subclasses MyBase:
MyDerived d;
float f = X::getFloat(d);
If I link the obj file contai... | This problem will occur when the lib and the executable have been be compiled with different definitions of the MyDerived class (i.e. different versions of the .h/.hh/.hpp file that declares MyDerived. Completely clean and rebuild your projects. Barring this, different compiler options could be responsible, though it... |
622,229 | 622,239 | error LNK2005: already defined - C++ | Background
I have a project named PersonLibrary which has two files.
Person.h
Person.cpp
This library produces a static library file. Another project is TestProject which uses the PersonLibrary (Added though project dependencies in VS008). Everything worked fine until I added a non-member function to Person.h. Person... | You either have to
move SetPersonName's definition to a .cpp file, compile and link to the resulting target
make SetPersonName inline
This is a well known case of One Definition Rule violation.
The static keyword makes the function's linkage internal i.e. only available to the translation unit it is included in. Thi... |
622,339 | 622,346 | Which is the best, standard (and hopefully free) C++ compiler? | Saludos a todos en stackoverflow.com!!
So... I'm a C++ newbie currently taking the subject of Data Structures, and I want to consult something with you guys:
Since I started studying Systems Engineering, I've been using the last version of Dev-C++ for all my programming projects. It has done it's job well so far, but i... | Code::Blocks - it's free, it's cross-platform, it's pretty good. You can download a package consisting of the CB IDE, the MinGW C++ compiler and the gdb debugger. Installation is very straightforward.
|
622,402 | 622,462 | boost thread compiler error with GCC | on linux, gcc 4.3, compiling a class with boost::thread implementation and mutexes / condition variables I get the following strange error, apparently due to type conflicts with the posix thread library:
*Compiling: filter.cpp
/usr/include/boost/thread/condition.hpp: In member function »void boost::condition::wait(L&) ... | You must wait on the bufferLock, not m_mutex:
while (!m_bStop)
m_change.wait(bufferLock);
Condition<>::wait() takes a ScopedLock as parameter, not a Mutex.
|
622,418 | 622,427 | How to deploy a Qt application on Windows? | So now I can make a .exe of my application. Now how do I get my application ready to deploy for windows?
This is meant to be the canonical question for Qt application deployment issues on Windows.
| The Qt documentation has pages for that:
Qt 5,
Qt 4.
|
622,592 | 622,666 | Win32 programming hiding console window | I'm learning C++ and I made a new program. I deleted some of my code and now my console window is not hidden. Is there a way to make it hide on startup without them seeing it?
| If you're writing a console program and you want to disconnect your program from the console it started with, then call FreeConsole. Ultimately, you probably won't be satisfied with what that function really does, but that's the literal answer to the question you asked.
If you're writing a program that you never want t... |
622,659 | 622,722 | What are the good and bad points of C++ templates? | I've been talking with friends and some completely agree that templates in C++ should be used, others disagree entirely.
Some of the good things are:
They are more safe to use (type safety).
They are a good way of doing generalizations for APIs.
What other good things can you tell me about C++ templates?
What bad thi... | Templates are a very powerful mechanism which can simplify many things. However to use them properly requires much time and experience - in order to decide when their usage is appropriate.
For me the most important advantages are:
reducing the repetition of code (generic containers, algorithms)
reducing the repetitio... |
622,762 | 627,400 | Running music as SDL_Mixer chunks | Currently, SDL_Mixer has two types of sound resources: chunks and music.
Apart from the API and supported formats limitations, are there any reasons not to load and play music as a SDL_Chunk and channel? (memory, speed, etc.)
| The API is the real issue. The "music" APIs are designed to deal with streaming compressed music, while the "sound" APIs aren't. Then again, if you manage to make it work in your app, then it works.
|
622,978 | 623,031 | Error in outputting to a file in C++ that I can't find | Not as in "can't find the answer on stackoverflow", but as in "can't see what I'm doing wrong", big difference!
Anywho, the code is attached below. What it does is fairly basic, it takes in a user created text file, and spits out one that has been encrypted. In this case, the user tells it how many junk characters to... | Further to the previous answers, I believe it's because the file you wish to encrypt is not being found by the original code. Is it safe to assume that you're running the code from the IDE? If so, then the file that is to be encrypted has to be in the same directory as the source.
Also:
outfile << putchar(33 + rand() %... |
623,040 | 623,060 | C++ development on linux - where do I start? | I decided to leave my windows install behind and am now running Debian as my default OS. I have always coded in Windows and specifically with Visual Studio. I am currently trying to get used to compiling my code under linux.
Although I still have a lot of documentation to read, and don't expect you guys to make it too ... |
What are recommended guides on creating a make file, how do I compile from this makefile (do I call g++ myself, do I use 'make'?)
You build from the makefile by invoking "make". And inside your makefile, you compile and link using g++ and ld.
Looking at other linux software, they almost always seem to have a 'config... |
623,127 | 623,160 | OpenGL coordinate problem | I am creating a simple 2D OpenGL application but I seem to be experiencing some camera issues. When I draw a rectangle at (20,20) it is drawn at (25,20) or so. When I draw it at (100, 20) it is drawn at 125 or so. For some reasons everything is being shifted to the right by a few %.
I have pasted a trimmed down version... | You need to set the projection matrix inside the reshape function (resize()), which also automatically solves the problem of the user resizing the window:
void resize(int w, int h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, w, h, 0);
}
And then in your draw function, make sure that the matrix... |
623,268 | 623,278 | C++: Searching in Process Memory | By already given specific process' handle, how can I move further to search for a specific keywords(bytes, ints(2 bytes), text(an array)) in its memory in code, using VC++ ?
| I take it you want to scan through another's process raw memory. By definition, processes are and should be isolated from one another and have totally independent address spaces (your address 0x06573AF8 contains something entirely different from the corresponsing address in another process' address space).
However, th... |
623,373 | 623,388 | Catching exception in code | I was trying this piece of code to check whether the divide by zero exception is being caught:
int main(int argc, char* argv[])
{
try
{
//Divide by zero
int k = 0;
int j = 8/k;
}
catch (...)
{
std::cout<<"Caught exception\n";
}
return 0;
}
When I complied this ... | Enable structured exception handling under project -> properties -> configuration properties -> c/c++ -> code generation -> enable c++ exceptions.
Use a try except. Ideally with a filter that checks the exception code then returns the constant signalling if it would like to catch. I have skipped that out here but I re... |
623,475 | 623,493 | Reverse engineer C++ DLL | I have a small utility that was originally written in VS2005.
I need to make a small change, but the source code for one of the dlls has been lost somewhere.
Is there a free or reasonably priced tool to reverse engineer the dll back to C++ code.
| Hex-Rays decompiler is a great tool, but the code will be quite hard to read and you will have to spend a lot of time to reverse engineer the whole DLL.
|
623,605 | 623,675 | C++ vim IDE. Things you'd need from it | I was going to create the C++ IDE Vim extendable plugin. It is not a problem to make one which will satisfy my own needs.
This plugin was going to work with workspaces, projects and its dependencies.
This is for unix like system with gcc as c++ compiler.
So my question is what is the most important things you'd need fr... |
debugger
source code navigation tools (now I am using http://www.vim.org/scripts/script.php?script_id=1638 plugin and ctags)
compile lib/project/one source file from ide
navigation by files in project
work with source control system
easy acces to file changes history
rename file/variable/method functions
easy access t... |
623,638 | 623,650 | Compiling a C++ .lib with only header files? | I'm compiling a C++ static library and as all the classes are templated, the class definitions and implementations are all in header files. As a result, it seems (under visual studio 2005) that I need to create a .cpp file which includes all the other header files in order for it to compile correctly into the library.
... | The compiler doesn't compile header files since these are meant to be included into source files. Prior to any compilation taking place the preprocessor takes all the code from any included header files and places that code into the source files where they're included, at the very location they're included. If the comp... |
623,692 | 623,783 | Handcode GUI or use gui-designer tool | I would like to hear some opinions on hand coding your GUIs as one typically do when using Java or Qt with C++, vs using a gui-designer tool? Examples of GUI designer tools would be MFC GUI-designer, Qt designer, Interface Builder (Apple).
I used to be a fan of hand coding but from recent experience I have switched. Th... | I feel strongly that you should use an interface builder instead of hand-coding a GUI. As in the question mentioned it's a much cleaner separation and once something has to be edited it's much easier.
The Qt Designer got this feature to create a class out of a .ui file1), but I think that not using this feature is the ... |
623,693 | 623,709 | Accessing struct members directly | I have a testing struct definition as follows:
struct test{
int a, b, c;
bool d, e;
int f;
long g, h;
};
And somewhere I use it this way:
test* t = new test; // create the testing struct
int* ptr = (int*) t;
ptr[2] = 15; // directly manipulate the third word
cout << t->c; // look if ... | It looks like you are asking two questions
Is it safe to treat &test as a 3 length int arrray?
It's probably best to avoid this. This may be a defined action in the C++ standard but even if it is, it's unlikely that everyone you work with will understand what you are doing here. I believe this is not supported if you... |
623,784 | 623,803 | How does one write the hex values of a char in ASCII to a text file? | Here is what I currently have so far:
void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
unsigned char *buf = (unsigned char*)ptr;
for( int i = 0; i < buflen; ++i ) {
if( i % 16 == 0 ) {
stream << prefix;
}
stream << buf[i] << ' ';
}
}
... | #include <iostream>
using namespace std;
int main() {
char c = 123;
cout << hex << int(c) << endl;
}
Edit: with zero padding:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
char c = 13;
cout << hex << setw(2) << setfill('0') << int(c) << endl;
}
|
623,903 | 623,932 | Defining a class within a namespace | Is there a more succinct way to define a class in a namespace than this:
namespace ns { class A {}; }
I was hoping something like class ns::A {}; would work, but alas not.
| You're close, you can forward declare the class in the namespace and then define it outside if you want:
namespace ns {
class A; // just tell the compiler to expect a class def
}
class ns::A {
// define here
};
What you cannot do is define the class in the namespace without members and then define the class a... |
623,929 | 623,961 | Which floating-point image format should I use? | In the past I've saved RGB images (generated from physical simulations) as 8-bits/channel PPM or PNG or JPEG.
Now I want to preserve the dynamic range of the simulation output, which means saving a floating point image and then treating conversion to 8-bits/channel as a post-processing step (so I can tweak the conversi... | Have you looked into Radiance RGBE (.hdr) and OpenEXR (.exr). RGBE has some source code here. NVIDIA and ATI both support EXR data in their graphics cards. There are source code and binaries from the OpenEXR download page. ILM created OpenEXR and it has wide support. OpenEXR has support for 16 and 32 bit floating ... |
624,037 | 624,056 | 32 bit Linux clock() overflow | I need to measure, in C++ on Linux (and other Unix-like systems), the CPU (not wall clock) time taken by a long computation, so I'm using clock(). Problem: on 32 bit systems, this wraps around after about 2000 or 4000 seconds.
What's the recommended workaround for this?
| You want to use getrusage which fills the following struct:
struct rusage {
struct timeval ru_utime; /* user time used */
struct timeval ru_stime; /* system time used */
...
};
For completion, struct timeval:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microsec... |
624,250 | 624,258 | How do I read / write gzipped files in C++? | How do I read / write gzipped files in C++?
The iostream wrapper classes here look good, and here is a simple usage example:
gz::igzstream in(filename);
std::string line;
while(std::getline(in, line)){
std::cout << line << std::endl;
}
But I wasn't able to actually link it (although I have a /usr/lib/libz.a). A simp... | Obviously you need the cpp-file where the gzstreambase destructor is defined as well, i.e. gzstream.cpp (that's the link fault). libz is just a c-api for gzip, it knows nothing of c++ stdlib streams.
Boost's iostream lib has gzip and bzip2 streams too.
EDIT: Updated the link to point to the latest version of the code t... |
624,260 | 624,291 | How to reuse an ostringstream? | I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?
| I've used a sequence of clear and str in the past:
// clear, because eof or other bits may be still set.
s.clear();
s.str("");
Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin:
s.clear();
s.seekp(0); // for outputs... |
624,348 | 625,371 | How can I build different versions of a project using the Jam make tool? | I have a C++ project that compiles to different versions, including release, debug, shared library, and executable, with different compiler flags for each. I am trying out Jam as an alternative to Make, because it looks like a simpler system.
Is Jam capable of this? The main problem is that it always places the .o fil... | I'm not familiar with Perforce's Jam however bjam allows this - and it's trivially easy. bjam does not place the intermediate files in the same directory as the source; it creates debug/release/static/shared directories depending on the type of project you're building.
For example if you wanted to build release and de... |
624,540 | 624,559 | Algorithm to return the maximum possible sum of subsequences in a sequence | int maxSumRec(const vector<int> &a, int left, int right){
if (left == right){
if (a[left] > 0){
return a[left];
}
else
return 0;
}
int center = (left + right)/2;
int maxLeftSum = maxSumRec(a, left, center);
int maxRightSum = ... |
in the first if statement, why return 0 if a[left] < 0?
Because then the empty subsequence has the maximum sum, which is 0.
|
624,691 | 624,697 | Passing a pointer to process spawned with exec() | I would like to pass a pointer (I am putting a file with data in memory with mmap) to processes spawned using fork + exec, but I am stuck on how to pass a pointer to the exec() spawned process?
UPDATE1:
Thanks for your inputs, I do use shared memory creating it with mmap with MAP_INHERIT flag:
Each mapped file and shar... | If you use shared memory, you can't pass the pointer. The pointer will contain the virtual address, which is different from one process to another. You have to exchange offset values, based on the start of the shared memory area.
If you don't use shared memory, you can't exchange pointers of any kind: The other proces... |
624,854 | 624,858 | static_cast with boost::shared_ptr? | What is the equivalent of a static_cast with boost::shared_ptr?
In other words, how do I have to rewrite the following
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);
when using shared_ptr?
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???
| Use boost::static_pointer_cast:
boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);
|
625,023 | 625,044 | C++ class best practice | I'd like to know some best practice when designing c++ classes.
To put it in context, I have a c++ class named Vec3.
class Vec3{
private:
float elements[3];
public:
Vec3(Vec3 v1){...}
Vec3(int x, int y, int z){...}
Vec3 add(Vec3 v1){...}
Vec3 add(int x, int y, int z){...}
...
Vec3 multiply(V... | These are the rules I usually stick to. Note 'usually', sometimes there are reasons for doing things differently...
For parameters I don't intend to modify I pass by value if they aren't too large since they will be copied. If they are a bit large or aren't copyable, you could use a const reference or a pointer (I pref... |
625,105 | 625,113 | Compact way to extract parts of strings (FASTA header) | Given the following string:
string Header =">day11:1:356617";
How do you extract everything except ">",
yielding only:
day11:1:356617
I could do standard loop over the string character
and keep only other than ">".
string nStr ="";
for (int i=0; i < Header.size(); i++) {
if (Header[i] != ">") {
nStr = ... | if (Header[0] == '>') Header = Header.substr(1);
|
625,247 | 625,261 | How do you read a word in from a file in C++? | So I was feeling bored and decided I wanted to make a hangman game. I did an assignment like this back in high school when I first took C++. But this was before I even too geometry, so unfortunately I didn't do well in any way shape or form in it, and after the semester I trashed everything in a fit of rage.
I'm look... | Here's a rough sketch, assuming that the words are separated by whitespaces (space, tab, newline, etc):
vector<string> words;
ifstream in("words.txt");
while(in) {
string word;
in >> word;
words.push_back(word);
}
string r=words[rand()%words.size()];
|
625,333 | 625,440 | How to limit the impact of implementation-dependent language features in C++? | The following is an excerpt from Bjarne Stroustrup's book, The C++ Programming Language:
Section 4.6:
Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation- defined (§C.2). I point out these dependencies and often recommend avoiding them or taking steps to minimize their impac... | Few ideas:
Unfortunately you will have to use macros to avoid some platform specific or compiler specific issues. You can look at the headers of Boost libraries to see that it can quite easily get cumbersome, for example look at the files:
boost/config/compiler/gcc.hpp
boost/config/compiler/intel.hpp
boost/config/pla... |
625,353 | 625,412 | Creating Map from Alternate Key Value Input | I have a data that looks like this:
>day11:1:356617
ACTTCTGATTCTGACAGACTCAGGAAGAAACCAT
>day11:2:283282
CTCAGCCCGTAGCCCGTCGGTTCCGGAGTAAGTT
>day11:3:205058
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
>day11:4:202520
AGTTCGATCGGTAGCGGGAGCGGAGAGCGGACCC
>day11:5:107099
AGGCATTCAGGCAGCGAGAGCAGAGCAGCGTAGA
>day11:6:106715
CTCTTTGCCCCAT... | You're cleaning Fasta, Header and Tag each loop. What you have to do is:
Declare those variables outside the while (just before it)
Change the if (Header != "" || Tag != "") line to using && instead of || (there is a logic error there)
Reset the Tag and Header variables when you add them to the map.
The correct code ... |
625,416 | 625,421 | Can you set the size of the call stack in c++? (vs2008) | I'm working from an example piece of code that allocates a relatively large local array. (32768 to be precise) When I try the same I'm getting behaviour that appears to be a stack overflow. Now I was wondering if my example has maybe set the stack to be larger then my application. Is this possible? if so how?
| With the Microsoft compiler you can use /F to set the stack size, however it seems like you should just allocate the object on the heap. You should have a reason you're allocating this on the stack rather than the heap.
Edit: This page gives a good cross-platform breakdown, though it may be dated.
|
625,504 | 625,514 | Can Events be Inter-Process? | I have created an event in one process and to test, sent the event handle via a pipe to a totally separate process (not a child thread)
When I fire the event in the first, WaitForSingleObject does not detect the event so I am guessing the answer is no unless I missed some trick in the SECURITY_ATTRIBUTES structure?
Or ... | You need to create a named event and open it in both processes. If you have multiple processes listening, you may consider using a semaphore.
|
625,507 | 625,521 | Static vs. member variable | For debugging, I would like to add some counter variables to my class. But it would be nice to do it without changing the header to cause much recompiling.
If Ive understood the keyword correctly, the following two snippets would be quite identical. Assuming of course that there is only one instance.
class FooA
{
publi... | Your assumptions about static function variables are correct. If you access this from multiple threads, it may not be correct. Consider using InterlockedIncrement().
|
625,616 | 625,634 | template default argument in a template | I am trying to compile this :
template <class T, class U = myDefaultUClass<T> >
class myClass{
...
};
Although it seems quite intuitive to me it is not for my compiler, does anyone knows how to do this ?
edit : Ok, the problem was not actually coming from this but from a residual try ... Sorry about this, thanks for... | The following works for me using g++. Please post more code, the error messages you are getting and the compiler version.
class A {};
template <class T> class T1 {};
template <class T, class U = T1<T> > class T2 {
};
T2 <A> t2;
|
625,799 | 628,079 | Resolve build errors due to circular dependency amongst classes | I often find myself in a situation where I am facing multiple compilation/linker errors in a C++ project due to some bad design decisions (made by someone else :) ) which lead to circular dependencies between C++ classes in different header files (can happen also in the same file). But fortunately(?) this doesn't happe... | The way to think about this is to "think like a compiler".
Imagine you are writing a compiler. And you see code like this.
// file: A.h
class A {
B _b;
};
// file: B.h
class B {
A _a;
};
// file main.cc
#include "A.h"
#include "B.h"
int main(...) {
A a;
}
When you are compiling the .cc file (remember that the ... |
625,849 | 625,868 | Why does the output fail to show the content of a variable after merely adding a cout line? | #include <iostream>
using namespace std;
class Marks
{
public:
char* name();
};
char* Marks::name()
{
char temp[30];
cout<<"Enter a name:"<<endl;
cin.getline(temp,30);
return temp;
}
int main ()
{
char *name;
Marks test1;
name=test1.name();
//cout<<"name:"; //uncomment this line... | The problem is because the value that name is pointing to has been destroyed. You are returning the address of a local variable from Marks::name(). Most likely a side affect of the first cout is causing the contents of name to be destroyed. You're probably just getting lucky when the first cout is commented out.
The co... |
625,990 | 626,265 | Are there any reasons not to use Visual Studio 6 for C++? | Are there any reasons why I shouldn't use Visual Studio 6 for C++ development?
Where can I find some resources why this would or wouldn't be a good idea?
Are there any lists of issues I would have with this?
|
std::string multicore/proc issues in the runtime, re: KB813810
poor STL support
even poorer Standard C++ support
Don't do it.
|
626,067 | 626,986 | Inheritance issues with template classes | Can anyone figure out a nice way to get the following code to work? (This is, once again, an incredibly simplified way of doing this)
template <class f, class g> class Ptr;
class RealBase
{
};
template <class a, class b, class c = Ptr<a,b> >
class Base : public RealBase
{
public:
Base(){};
};
template <class d... | OK. After trying about 10 different methods (static_cast, reinterpret_cast etc.) you can just cast it.
int main()
{
Base<int,int> b = Base<int,int>();
Derived<double,double> d = Derived<double,double>();
DDerived dd = DDerived();
Ptr<double,double> p(&dd);
DDerived * fauxpointer;
... |
626,123 | 626,138 | Question on using realloc implementation in C++ code | Friends
In our C++ , Iam current using realloc method to resize the memory allocated by malloc.
realloc() usage is done as below
my_Struct *strPtr =(my_struct*)malloc(sizeof(my_Struct));
/* an later */
strPtr = (my_struct*)realloc(strPtr,sizeof(my_Struct)*NBR);
now wikipeadia (_http://en.wikipedia.org/wiki/Malloc)s... | Of course you must protect against the case that realloc() returns NULL. It is a memory allocation, and in C (where realloc()) is mostly used, I think C++ programmers think it is a bit low-level/qaint to use raw realloc() calls, memory allocations can always fail.
Directly overwriting the pointer with the return value ... |
626,160 | 626,289 | Threading in a DLL where the DLL must return before child thread finishes | I am working on writing a wrapper DLL to interface a communication DLL for a yokogawa WT1600 power meter, to a PC based automation package. I got the communication part to work but I need to thread it so that a 50ms scan time of the automation package can be maintained. (The Extended Function Block (EFB) Call will bloc... | Any thread created (whether in a DLL or elsewhere) will not stop spontaneously. In particular, the function that created the thread may return. The new thread would still run even if the creator thread exited. That is, assuming it didn't hit the end of its entry function.
Windows threads return a DWORD when ready. To p... |
626,199 | 626,215 | Overloading << operator C++ - Pointer to Class | class logger {
....
};
logger& operator<<(logger& log, const std::string& str)
{
cout << "My Log: " << str << endl;
return log;
}
logger log;
log << "Lexicon Starting";
Works fine, but i would like to use a pointer to a class instance instead. i.e.
logger * log = new log();
log << "Lexicon Starting";
Is th... | You'd have to dereference the pointer to your logger object and obviously check if it's not 0. Something like this should do the job:
log && ((*log) << "Lexicon starting")
As a general aside, I would shy away from referencing objects like a logger (which you normally unconditionally expect to be present) via a poin... |
626,345 | 8,786,996 | Cannot load symbols in GlowCode x64 | This question might be too application specific to be out here on SO, but here goes.
I am trying to profile a simple native c++ application using GlowCode-x64 6.2 .
The problem is that no matter which settings I set in the "Options->Symbol server and search path" the symbols are never loaded. My .pdb files are all in ... | I visited the GlowCode site and found that version 6.2 is only 32 bit build and not 64. GlowCode 7.0 has both the installers, 32 bit and 64 bit. This might be your problem.
|
626,373 | 626,413 | How to conditionally choose the C# class I invoke via COM in my C++ DLL? | After much help from all my StackOverFlow brethren, I managed to create a C++ DLL that calls my C# classes via COM and passes data back and forth to an external application. There was much celebration in the kingdom after that code started working.
Now I have a new problem. I'm expanding the DLL so that it can call dif... | Do smth like this:
GUID classId = GUID_NULL;
if( strcmp( modelType, "Model1" ) == 0 ) {
classId = __uuidof( class1 );
} else if( strcmp( modelType, "Model2" ) == 0 ) {
classId = __uuidof( class2 );
} else if(... etc, continue for all possible model types
}
IUnitModelPtr unit;
unit.CreateInstance( classId );
// ... |
626,510 | 626,521 | What is the impact of namespaces in c++ linkages compared to linkages in c? | What is the impact of namespaces in c++ linkages compared to linkages in c?
Is it possible to make a name that has internal linkage to external linkage just by using namespace.Similarly the other way around.
| In general, namespace name is prepended to any enclosed entity's name before the name is mangled and goes to the linker.
If you have two functions with the same signatures in different namespaces they link into one file just fine. If you have two classes with the same name and at least one method with the same signatur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.