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 |
|---|---|---|---|---|
2,762,141 | 2,762,150 | Looking at the C++ new[] cookie. How portable is this code? | I came up with this as a quick solution to a debugging problem - I have the pointer variable and its type, I know it points to an array of objects allocated on the heap, but I don't know how many. So I wrote this function to look at the cookie that stores the number of bytes when memory is allocated on the heap.
templa... | It is not even remotely portable.
An implementation can perform heap bookkeeping however it wants and there is absolutely no way to portably get the size of a heap allocation unless you keep track of it yourself (which is what you should be doing).
|
2,762,276 | 2,763,282 | Create a CBitmap from Resources ID | I need to fill a CImageList with a number of bitmaps which are stored in separate bmp files (rather than as a single bmp with numerous parts). I assume I need to create a CBitmap so I can call the Add method of CImageList. So how might one create a CBitmap object using only MFC Resource IDs?
| You just need to use the method CBitmap::LoadBitmap.
You can either load the bitmap from the file or from resources.
|
2,762,433 | 2,762,753 | How to call a particular function depending on a particular object's type | class Message {};
class BuildSandCastle : public Message {};
class DigHole : public Message {};
Given an arbitrary Message* object, how can I call a function of the same name doMessage() without resorting to switch logic or making a MessageHandler class that has one 'do' function for every message name?
EDIT: for exam... | I was looking for something like this
class MessageHandlerBase
{};
template<typename MessageType>
class MessageHandler:
public virtual MessageHandlerBase
{
virtual void process(MessageType*)=0;
};
class Message
{
protected:
template<typename MessageType>
void dynamicDispatch(MessageHandlerBase* handl... |
2,762,568 | 2,762,596 | C/C++ include header file order | What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
| I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order,... |
2,762,920 | 2,762,937 | error C2065: undeclared identifier | Currently, I have this function inside my other cpp file:
UINT32 functionHtml(const wchar_t *url)
{
WinHttpClient client(url);
client.SendHttpRequest();
wstring httpResponseHeader = client.GetHttpResponseHeader();
wstring httpResponse = client.GetHttpResponse();
writeToLog(httpResponse... | You are going to need to convert vUrl from VARIANT* (not familiar with that type) to an object of type const wchar_t*, and invoke functionHtml on that resulting object. The reason you got an "undeclared identifier" error is that you attempted to invoke functionHtml(url), despite the fact that there is no variable named... |
2,762,950 | 2,764,839 | Make All Types Constant by Default in C++ | What is the simplest and least obtrusive way to indicate to the compiler, whether by means of compiler options, #defines, typedefs, or templates, that every time I say T, I really mean T const? I would prefer not to make use of an external preprocessor. Since I don't use the mutable keyword, that would be acceptable to... | Take an open source C++ compiler and modify it.
I think the main reason for the downvotes is that people think you're trying to modify C++. Tell them instead you're creating a new language called "C-const" as a university project.
Personally I think it's an interesting idea - you can gain all sorts of performance and r... |
2,763,036 | 2,763,054 | Userdefined function for printf | Is it possible to replace printf with userdefined function or is it possible to create function similar like printf
| Sure, you can define variadic functions (the technical name for functions with a variable number of arguments, like printf) -- the URL I've pointed to is one reference for how to do it.
|
2,763,117 | 2,763,647 | how to find 2 to the power of n . n ranges from 0 to 200 | Assume my system as 32 bit machine. Considering this if I use long int for n>63 I will get my value as 0. How to solve it?
| double is perfectly capable of storing powers of two up to 1023 exactly. Don't let someone tell you that floating point numbers are somehow always inexact. This is a special case where they aren't!
double x = 1.0;
for (int n = 0; n <= 200; ++n)
{
printf("2^%d = %.0f\n", n, x);
x *= 2.0;
}
Some output of the pr... |
2,763,193 | 2,763,269 | Function declaration in C and C++ | I have two C++ files, say file1.cpp and file2.cpp as
//file1.cpp
#include<cstdio>
void fun(int i)
{
printf("%d\n",i);
}
//file2.cpp
void fun(double);
int main()
{
fun(5);
}
When I compile them and link them as c++ files, I get an error "undefined reference to fun(double)".
But when I do this as C ... | This is most likely because of function overloading. When compiling with C, the call to fun(double) is translated into a call to the assembly function _fun, which will be linked in at a later stage. The actual definition also has the assembly name _fun, even though it takes an int instead of a double, and the linker wi... |
2,763,259 | 2,763,389 | Creating Custom QT Library | I created a static Qt library by using VS2005.
It created an extra file "test_global.h" besides expected ones(test.h and test.cpp).
test_global.h
#ifndef TEST_GLOBAL_H
#define TEST_GLOBAL_H
#include <Qt/qglobal.h>
#ifdef TEST_LIB
# define TEST_EXPORT Q_DECL_EXPORT
#else
# define TEST_EXPORT Q_DECL_IMPORT
#endif
#end... | You mark your class (or methods) as exported in your library headers:
class TEST_EXPORT TestClass {
// ...
};
Then in your library pro file you add:
DEFINES += TEST_LIB
So during the dll compilation your class header will have "Q_DECL_EXPORT" macro which is Qt way to tell the linker "export this class/method", an... |
2,763,275 | 2,763,298 | Is the C++ compiler optimizer allowed to break my destructor ability to be called multiple times? | We once had an interview with a very experienced C++ developer who couldn't answer the following question: is it necessary to call the base class destructor from the derived class destructor in C++?
Obviously the answer is no, C++ will call the base class destructor automagically anyway. But what if we attempt to do th... | Standard 12.4/14
Once a destructor is invoked for an
object, the object no longer exists;
the behavior is undefined if the
destructor is invoked for an object
whose lifetime has ended (3.8).
So I guess the compiler should be free to optimize away the setting of buffer to null since the object no longer exists... |
2,763,398 | 2,763,426 | When I overload the assignment operator for my simple class array, I get the wrong answer I expect | //output is "01234 00000" but the output should be or what I want it to be is
// "01234 01234" because of the assignment overloaded operator
#include <iostream>
using namespace std;
class IntArray
{
public:
IntArray() : size(10), used(0) { a= new int[10]; }
IntArray(int s) : size(s), used(0) { a= new int[s]; }
i... | I think that the problem is that nowhere in your code sets used to anything other than 0 so when you loop from 0 to used nothing is copied.
Do you mean to set used when you assign to an element in operator[] ?
Also, if it's necessary to define a destructor and a copy-assignment operator then you usually (and in this ca... |
2,763,709 | 2,763,790 | CInternetSession::OpenURL exception if headers are defined. Works fine if not. Why? | Trying to log the application version details in our weblogs using the headers:
Should be a one liner..but for some reason whenever I specify anything but NULL for the headers it causes an exception (InternetOpenUrl() call returns NULL) - anyone able to explain why?
CInternetSession internet;
CHttpFile * pHttpFile;... | Does your CString resolve to CStringA or CStringW? If the latter (i.e. wide-char), here's a bit from MSDN (http://msdn.microsoft.com/en-us/library/aa384247%28VS.85%29.aspx):
If
dwHeadersLength is -1L and lpszHeaders
is not NULL, the following will
happen: If HttpSendRequestA is called,
the function assumes tha... |
2,763,824 | 2,764,052 | decltype, result_of, or typeof? | I have:
class A {
public:
B toCPD() const;
And:
template<typename T>
class Ev {
public:
typedef result_of(T::toCPD()) D;
After instantiating Ev<A>, the compiler says:
meta.h:12: error: 'T::toCPD' is not a type
neither decltype nor typeof work either.
| Since whatever result you obtain depends on the template parameter, typedef typename is necessary.
decltype is a standard C++11 feature. It is an "operator" which takes an expression and returns a type.
typedef typename decltype( T().toCPD() ) D; // can't use T:: as it's nonstatic
If T() isn't a valid (T not default-c... |
2,763,827 | 2,767,236 | How to force Mac window to foreground? | How can I programmatically force a mac window to be the front window? I have the window handle, and want to ensure that my window is displayed above all other windows. I can use both Carbon & Cocoa for this.
| For Cocoa, you can set the window level using:
[window setLevel:NSFloatingWindowLevel];
A floating window will display above all other regular windows, even if your app isn't active.
If you want to make your app active, you can use:
[NSApp activateIgnoringOtherApps:YES];
and
[window makeKeyAndOrderFront:nil];
|
2,763,836 | 2,781,399 | SFINAE failing with enum template parameter | Can someone explain the following behaviour (I'm using Visual Studio 2010).
header:
#pragma once
#include <boost\utility\enable_if.hpp>
using boost::enable_if_c;
enum WeekDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};
template<WeekDay DAY>
typename enable_if_c< DAY==SUNDAY, bool >::type goToW... | Works fine in GCC 4.2.1.
Looks like either VC's template engine is missing comparison operators for enum types, or it sloppily converted the enum to int and then decided to be strict and disallow implicit conversion to int (apparently with an exception for 0 and 1).
|
2,763,841 | 2,763,857 | C++ performance, optimizing compiler, empty function in .cpp | I've a very basic class, name it Basic, used in nearly all other files in a bigger project. In some cases, there needs to be debug output, but in release mode, this should not be enabled and be a NOOP.
Currently there is a define in the header, which switches a makro on or off, depending on the setting. So this is defi... | As with all questions like this, the answer is - if it really matters to you, try the approach and examine the emitted assembly language.
|
2,763,930 | 2,764,044 | Arrays of pointers to arrays? | I'm using a library which for one certain feature involves variables like so:
extern const u8 foo[];
extern const u8 bar[];
I am not allowed to rename these variables in any way.
However, I like to be able to access these variables through an array (or other similar method) so that I do not need to continually hardcod... | An array of pointers to arrays only works if foo and bar have exactly the same size, and that size is known at compile time in your translation unit.
const u8 (*pl[])[32] = {&foo, &bar};
If that is not the case, you must use an array of pointers to bytes.
const u8 *pl[] = {foo, bar};
|
2,763,932 | 2,764,070 | Storing images and pointers in OpenCV | I have a loop which goes through a video with some processing/calculations of the images. I want to save the image in the loop with the highest value from the processing, but I'm struggling a bit with storing the image temporally while the loop finishes.
The images/frames are initialized like this
IplImage* frame = 0;
... | probably the frame IplImage* gets recycled by OpenCv internal referencing system. Have you tried to do a deep copy of the image, using IplImage* cvCloneImage(const IplImage* image)?
By the way, with openCv 2.0 and up it's better if you use a cvMat (or cv::Mat) to hold images... Use then cv::Mat image, then image.clon... |
2,763,987 | 2,764,199 | How to copy files in Visual C++? | I am using Visual C++. How to copy the content of this file to another file?
UINT32 writeToLog(wstring log)
{
wfstream file1 (LOG_FILE_NAME, ios_base::out);
file1 << log;
file1.close();
// want to copy file1 to file2
return 0;
}
| What exactly do you want to do? If you need a copy of the data, you can read it in and write it back out again. If you really need a copy of the file, you have to use OS specific calls.
In many cases, reading in the file data and then writing it out again to a different file is a close enough approximation to a copy - ... |
2,764,077 | 2,985,024 | boost::asio::local::stream_protocol::iostream does not work? | Referencing an old (from 2008) discussion:
There is a compile error when trying to use boost::asio::local::stream_protocol::iostream
There was no solution on the discussion forum and I've run into the same problem, it seems.
Has there been a fix or solution for the compile error? How can I use
boost::asio::local::strea... | This bug was reported on the boost trac webiste. Chris closed it as invalid and suggested using the existing boost::asio::local::stream_protocol examples.
|
2,764,108 | 2,764,153 | Why does double dispatch not work in C++? | #include<iostream.h>
#include<conio.h>
using namespace std;
class SpaceShip {};
class GiantSpaceShip : public SpaceShip {};
class Asteroid {
public:
virtual void CollideWith(SpaceShip *) {
cout << "Asteroid hit a SpaceShip" << endl;
}
virtual void CollideWith(GiantSpaceShip *) {
cout << "Asteroid hit a... | This is not single dispatch but double dispatch: you want the method to depend both on the actual/real type of the object it is invoked on, and on the actual/real type of the argument.
This issue can be solved by the Visitor design pattern.
|
2,764,112 | 2,764,166 | SHCreateStreamOnFileEx linker error | I am getting linker error while working on SHCreateStreamOnFileEx.
Please help me to find out the problem.
IStream* replace::GetStream()
{
LPCWSTR pszFile=L"D:\\Test\\output.txt";
IStream* dataStream = NULL;
if (dataStream == NULL)
{
SHCreateStreamOnFileEx(pszFile,
STGM_READ|STGM_SHARE_DENY_NONE|STGM_DEL... | Adding the matching LIB file to your project settings should do the trick. Open the project settings -> linker -> input -> additional dependencies and add the Shlwapi.lib to the list.
As an alternative you can also put the following directive into your cpp file:
#pragma comment(lib, "Shlwapi.lib");
|
2,764,337 | 2,764,362 | Link error (LNK2019) when including other projects in Visual Studio 2005 | I am trying to work with several projects on visual studio 2005. I have one project that depends on two others. I have included those two project in the first project solution, and set the dependencies correctly.
I get this error when linking the project:
1>server_controller.obj : error LNK2019: unresolved external sy... | How did you set dependencies? In C++ you need to set linker dependencies in Project - Properties - Linker - Additional libraries. Add required .lib files here.
About solution Dependencies dialog: it only affects projects build order, but doesn't resolve linker dependencies.
|
2,764,607 | 2,764,631 | how to traverse a file in python and c++ in backward way? And also store data in backward (bottom to top) way? | Suppose i want to store 3 lines in a file both in python and C++ .
I want to store it like this
aaa
bbb
ccc ..
But i am giving ccc input first then bbb then aaa. How will I traverse the file from bottom to top and also store from bottom to top/?
| It isn't obvious from the title and question whether you want to store to a file, load from a file, or both, so I'll cover both cases:
Reading
If it's OK to load it all into memory at once (in Python):
list(reversed(list(open('foo.txt'))))
Otherwise, it gets a lot more difficult. Processing a file backwards requires t... |
2,764,671 | 2,765,091 | creating an array which can hold objects of different classes in C++ | How can I create an array which can hold objects of different classes in C++?
| If you want to create your own, wrap access to a pointer/array using templates and operator overloading. Below is a small example:
#include <iostream>
using namespace std;
template <class T>
class Array
{
private:
T* things;
public:
Array(T* a, int n) {
things = new T[n];
for (int i=0; i<n; ... |
2,764,806 | 2,764,974 | Object Deletion: use parent or not | Which one do you prefer to delete objects? Especially in QT, but other practices are also welcome. These two alternatives seem same to me, are they?
Bound to another class, and destroy when it is destroyed.
SomeClass::SomeClass{
socket_ = new QTcpSocket(this);
}
or
Destroy in the destructor of class
SomeClass::So... | When in Rome, do as the Romans do. If your framework uses one method (for example Qt relies on parent-child relationship), use this method in your code.
Of course don't forget about general good memory management practices: create object on stack whenever it's possible, use shared pointers, etc.
|
2,764,940 | 2,766,292 | Adding a transparent bitmap to a windows button | It's a while since I've done this, but I'm trying to add a custom button graphic to a windows button, with some transparent areas. I've tried various schemes but can't seem to get the transparent areas to show. Here's my code:
hbmpUpDisabled = LoadImage(instance,MAKEINTRESOURCE(IDB_UPARROWDISABLED), IMAGE_BITMAP, 0, ... | LR_LOADMAP3DCOLORS should map grey - in the source image - to to the current button face color. Buttons do not use AlphaBlt or TransparentBlt so there is no way to actually (short of custom painting) set a bitmap with transparent or alpha'd areas onto a button and expect it to work. You just have to pre-prepare the bit... |
2,765,164 | 2,765,211 | inline vs __inline vs __inline__ vs __forceinline? | What are the differences between these four inline (key)words?
inline, __inline, __inline__, __forceinline.
| inline is the keyword, in C++ and C99.
__inline is a vendor-specific keyword (e.g. MSVC) for inline function in C, since C89 doesn't have it.
__inline__ is similar to __inline but is from another set of compilers.
__forceinline is another vendor-specific (mainly MSVC) keyword, which will apply more force to inline the ... |
2,765,205 | 2,765,644 | Splitting a double vector into equal parts | Greetings,
Any input on a way to divide a std::vector into two equal parts ? I need to find the smallest possible difference between |part1 - part2|.
This is how I'm doing it now, but from what you can probably tell it will yield a non-optimal split in some cases.
auto mid = std::find_if(prim, ultim, [&](double temp) -... | Given that:
The vector is sorted, highest to lowest, values can indeed appear twice.
I'm not expecting part1 and part2 to have the same numbers of elements, but
sum(part1) should be as close as possible to sum(part2)
This is not optimal, but it will provide a reasonable approximation for values such as those you have g... |
2,765,403 | 2,765,765 | Visual Studio 2010 library linking order | How do you specify, in Visual Studio 2010, the order in which library files should be linked?
I have a project that links against libexpat and against another library. This library (not under my control) seems to also include libexpat. The problem is that 'we' use a different version of the library (XML_UNICODE vs not)... | I have found 'a' solution: if you add the libraries through #pragma comment(lib... the order of linking is the same as the order in which you type those pragma's. I'm still keeping the question open for a solution when the libraries are added through the project file instead of through pragma statements.
|
2,765,462 | 2,765,613 | How to cin Space in c++? | Say we have a code:
int main()
{
char a[10];
for(int i = 0; i < 10; i++)
{
cin>>a[i];
if(a[i] == ' ')
cout<<"It is a space!!!"<<endl;
}
return 0;
}
How to cin a Space symbol from standard input? If you write space, program ignores! :(
Is there any combination of symbols (e.g. '\s... | It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws, as follows:
cin >> noskipws >> a[i];
But, since you seem like you want to look at the individual characters, I'd sugges... |
2,765,779 | 2,765,799 | C++ Any way to store different templated object into the same container | Is there any hack I could use to do this:
template <class TYPE>
class Hello
{
TYPE _var;
};
I would like a way to store
Hello<int> intHello and Hello<char*> charHello
into the same Container such as a Queue / List.
| No, because they are different and completely unrelated types.
You can, however, use inheritance and smart pointers:
class HelloBase
{
public:
virtual ~HelloBase();
}
template <class TYPE>
class Hello : public HelloBase
{
TYPE _var;
}
std::vector<boost::shared_ptr<HelloBase> > v;
shared_ptr may be supporte... |
2,765,952 | 2,801,387 | C++ Virtual Constructor, without clone() | I want to perform "deep copies" of an STL container of pointers to polymorphic classes.
I know about the Prototype design pattern, implemented by means of the Virtual Ctor Idiom, as explained in the C++ FAQ Lite, Item 20.8.
It is simple and straightforward:
struct ABC // Abstract Base Class
{
virtual ~ABC() {}
... | FYI, this is the design I came out with. Thank you Paul and FredOverflow for your inputs. (And Martin York for your comment.)
Step #1, Compile-time polymorphism with templates
Polymorphism is performed at compile-time using templates and implicit-interfaces:
template< typename T >
class ImgOp
{
T m_t; // Not a ptr:... |
2,766,022 | 2,766,741 | Linking Libraries with Duplicate Class Names using GCC | Is there a way for GCC to produce a warning while linking libraries that contain classes with the same name? For example
Port.h
class Port {
public:
std::string me();
};
Port.cpp
#include "Port.h"
std::string Port::me() { return "Port"; }
FakePort.h
class Port {
public:
std::string me();
};
FakePort.cpp
#include... | The following might be worth a try (I honestly don't know if it'll do what you want):
--whole-archive
For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally ... |
2,766,272 | 2,766,432 | Why is std::numeric_limits<T>::max() a function? | In the C++ Standard Library the value std::numeric_limits<T>::max() is specified as a function. Further properties of a specific type are given as constants (likestd::numeric_limits<T>::is_signed). All constants that are of type T are given as functions, whereas all other constants are given as, well, constant values.
... | To expand on Neil's remark, std::numeric_limit<T> is available for any number type including floating point numbers, and if you dig through the comp.lang.c++ thread, you'll see the mention that it might not be possible to define the static variables for floating point values.
So, for consistency they decided to put bot... |
2,766,579 | 2,766,624 | Porting Windows platform C++ to POSIX (Linux) C++ - WSAGetLastError() | I am currently porting some Windows mobile C++ code to standard C++.
So I am trying to find alternatives for windows specific functions.
I have had very little luck in finding a standard C++ function that can help me replace the WSAGetLastError() windows specific function.
WSAGetLastError() returns error numbers for er... | There are no Standard C++ functions supporting sockets. However, the POSIX socket functions should all set the errno variable on error - you just need to examine this - it should be declared in errno.h.
|
2,766,603 | 2,767,061 | Using WINAPI ReadConsole | I am trying to use the WINAPI ReadConsole() to wait for any keypress at the end of my Win32 console application.
CONSOLE_READCONSOLE_CONTROL tControl;
char pStr[65536];
DWORD dwBufLen = 1;
DWORD dwCtl;
tControl_c.nLength = sizeof( CONSOLE_READCONSOLE_CONTROL );
tControl_c.nInitialChars = 0;
tControl_c.dwControlKeyStat... | Works fine for me. The only way I could get it to fail with ERROR_INVALID_HANDLE was to pass it the STD_OUTPUT_HANDLE instead of the STD_INPUT_HANDLE. Are you sure hConsole_c is the input handle?
|
2,766,653 | 2,766,674 | What elegant method callback design should be used? | I'm surprised this question wasn't asked before on SO (well, at least I couldn't find it).
Have you ever designed a method-callback pattern (something like a "pointer" to a class method) in C++ and, if so, how did you do it ?
I know a method is just a regular function with some hidden this parameter to serve as a conte... | boost::function for single callback, boost::signal or boost::signals2 when more than one callbacks can be registered, using boost::bind to bind member methods (or adapting the signatures in different ways).
If you have access to a compiler with C++0x/C++11 support it may have std::function and std::bind that are the ne... |
2,766,722 | 2,766,776 | writing a single line of a file in C++ into two different arrays | suppose a text file has 11001100 11001101
and i open the text file and take the input from the file as pt[0]=11001100, pt[1]=11001101..
but if i take the input from file as in>>pt it wont put it in two different arrays which is obvious but it takes the whole line . Thus I have to take another for loop and traverse ... | Read it one byte at a time (e.g. with fread()). Append each byte to pt[i], where i is incremented when a space is encountered.
|
2,766,731 | 2,766,749 | What exactly do "IB" and "UB" mean? | I've seen the terms "IB" and "UB" used several times, particularly in the context of C++. I've tried googling them, but apparently those two-letter combinations see a lot of use. :P
So, I ask you...what do they mean, when they're said as if they're a bad thing?
| IB: Implementation-defined Behaviour. The standard leaves it up to the particular compiler/platform to define the precise behaviour, but requires that it be defined.
Using implementation-defined behaviour can be useful, but makes your code less portable.
UB: Undefined Behaviour. The standard does not specify how a prog... |
2,766,821 | 2,766,837 | Working with operator[] and operator= | Given a simple class that overloads the '[ ]' operator:
class A
{
public:
int operator[](int p_index)
{
return a[p_index];
}
private:
int a[5];
};
I would like to accomplish the following:
void main()
{
A Aobject;
Aobject[0] = 1; // Problem here
}
How can I overload the assignment ... | You don't overload the = operator. You return a reference.
int& operator[](int p_index)
{
return a[p_index];
}
Make sure to provide a const version as well:
const int& operator[](int p_index) const
{
return a[p_index];
}
|
2,767,035 | 2,767,188 | Programmatically create and launch and RDP session (without gui) | I'd like to know if there is a way to create and launch a Remote Desktop Session on a Windows Server programmatically.
I'm trying to make an automatic tool to create Local Users and then launch the associate RDP session. I've already made LocalUser creation and adding them to Remote Desktop Users (using net.exe).
But I... | You can use the Remote Desktop ActiveX control to connect, you would need to host it in a Form but the form wouldn't need to be visible. For an example see http://www.codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx
|
2,767,094 | 2,767,110 | Problem creating an array of objects C++ | I have a class and I want to create an array of a number instances, specifically a matrix class:
class Matrix {
public:
Matrix(int sizeX, int sizeY);
Matrix();
~Matrix();
....//omiting the rest here
private:
int dx, dy;
float **p
void allocArrays() {
assert(dx>0);
assert(... | Your Matrix(int, int) constructor has all default-able arguments, which would make it as callable as the default constructor. You should either get rid of the default constructor, or make it so that at least one of the arguments to Matrix(int, int) is required.
|
2,767,139 | 2,767,216 | How to pass array to function without variable instantiation, in C++ | Can I do this in C++ (if yes, what is the syntax?):
void func(string* strs) {
// do something
}
func({"abc", "cde"});
I want to pass an array to a function, without instantiating it as a variable.
| It can't be done in the current C++, as defined by C++03.
The feature you are looking for is called "compound literals". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++.
A similar feature is planned for C++ as well, but it is not there yet.
|
2,767,298 | 2,767,315 | C++ - repeatedly using istringstream | I have a code for reading files with float numbers on line stored like this: "3.34|2.3409|1.0001|...|1.1|". I would like to read them using istringstream, but it doesn't work as I would expect:
string row;
string strNum;
istringstream separate; // textovy stream pro konverzi
while ( getline(file,row) ) {
... | After setting the row into the istringstream...
separate.str(row);
... reset it by calling
separate.clear();
This clears any iostate flags that are set in the previous iteration or by setting the string.
http://www.cplusplus.com/reference/iostream/ios/clear/
|
2,767,329 | 2,767,420 | C++ template parameter/class ambiguity | while testing with different version of g++, the following problem came up
template<class bra>
struct Transform<bra, void> : kernel::Eri::Transform::bra {
static const size_t ni = bra::A::size;
bra::A is interpreted as kernel::Eri::Transform::bra::A, rather than template argument by g++ 4.1.2. on the other h... | Seems to me like gcc 4.1.2 was right. §14.6.1/7 (ISO/IEC 14882, C++03):
In the definition of a class template or in the definition of a member of such a template that appears outside of the template definition, for each base class which does not depend on a template-parameter (14.6.2), if the name of the base class or... |
2,767,403 | 2,767,418 | Is it standard C++ to assign a member pointer to the address of another member in the constructor initializer? | Does this conform to the standard?
class Foo {
Bar m_bar;
Bar * m_woo;
public:
Foo() : m_bar(42, 123), m_woo(&m_bar) { }
};
| It is correct. What is not correct is dereferencing that pointer before that particular subobject has been fully initialized.
|
2,767,443 | 2,770,002 | How to Elegantly convert switch+enum with polymorphism | I'm trying to replace simple enums with type classes.. that is, one class derived from a base for each type. So for example instead of:
enum E_BASE { EB_ALPHA, EB_BRAVO };
E_BASE message = someMessage();
switch (message)
{
case EB_ALPHA: applyAlpha();
case EB_BRAVO: applyBravo();
}
I want to do this:
Base* messa... | Well, after giving in to dynamic_cast and multiple inheritance, I came up with this thanks to Anthony Williams and jogear.net
class HandlerBase
{
public:
virtual ~HandlerBase() {}
};
template<typename T> class Handler : public virtual HandlerBase
{
public:
virtual void process(const T&)=0;
};
class MessageBas... |
2,767,525 | 2,767,589 | Friendness and derived class | Let's say I have the following class hierarchy:
class Base
{
protected:
virtual void foo() = 0;
friend class Other;
};
class Derived : public Base
{
protected:
void foo() { /* Some implementation */ };
};
class Other
{
public:
void bar()
{
Derived* a = new Derived();
a->foo(... | When you qualify a method name with a class name, as in Base::foo() dynamic dispatch (run-time binding) does not apply. It will always call the Base implementation of foo(), no matter if foo() is virtual or not. Since in this case it is pure virtual, there is no implementation and the compiler complains.
Your second pr... |
2,767,576 | 2,767,761 | friend declaration in C++ | In Thinking in C++ by Bruce eckel, there is an example given regarding friend functions as
// Declaration (incomplete type specification):
struct X;
struct Y {
void f(X*);
};
struct X { // Definition
private:
int i;
public:
friend void Y::f(X*); // Struct member friend
};
void Y::f(X* x) {
x->i = 47;
}
Now he explai... | The parameter types for function declarations may be incomplete.
For data member declarations and all definitions however, the type has to be complete:
struct A;
struct B {
void f(A); // declaration, fine
void g(A) {} // error
A a; // error
};
|
2,767,599 | 2,767,611 | I'm having trouble with using std::stack to retrieve the values from a recursive function | Thanks to the help I received in this post:
How do I use "this" in a member function?
I have a nice, concise recursive function to traverse a tree in postfix order:
void Node::postfix()
{
if (left != __nullptr) { left->postfix(); }
if (right != __nullptr) { right->postfix(); }
cout<<ca... | They are member functions:
s.top()
s.pop()
^ need parentheses to call a function
That's what the error means when it says "function call missing argument list." The argument list (which in this case is empty since the function takes no parameters) and the parentheses are missing.
|
2,767,612 | 2,767,646 | is it possible to apply an RC5 algorithm on an audio file in c++? | is it possible to encrypt an audio file in c++ using rc5?
| Yes. Crypto++ is an encryption library for C++. It supports RC5 and RC6. The fact that it is an audio file is of no importance.
|
2,767,777 | 2,767,829 | How to track down COM memory leak | I'm trying to track down a memory leak in a COM object, and I'm not seeing anything obviously wrong. I'm probably using some of the COM wrappers incorrectly, but my standard toolkit of finding memory leaks (AQtime) isn't helping me with COM. Does anyone have any tricks/tools to track down COM memory/reference leaks?
| If you're using ATL you can define _ATL_DEBUG_INTERFACES (see MSDN entry). This will certainly help you to catch any leaked interfaces, although obviously it won't help to catch any resources leaked internally within the object.
|
2,768,096 | 2,768,147 | delay loop output in C++ | I have a while loop that runs in a do while loop. I need the while loop to run exactly every second no faster no slower. but i'm not sure how i would do that. this is the loop, off in its own function. I have heard of the sleep() function but I also have heard that it is not very accurate.
int min5()
{
int second =... | The best accuracy you can achieve is by using Operating System (OS) functions. You need to find the API that also has a callback function. The callback function is a function you write that the OS will call when the timer has expired.
Be aware that the OS may lose timing precision due to other tasks and activities th... |
2,768,151 | 2,768,208 | Recursion problem overloading an operator | I have this:
typedef string domanin_name;
And then, I try to overload the operator< in this way:
bool operator<(const domain_name & left, const domain_name & right){
int pos_label_left = left.find_last_of('.');
int pos_label_right = right.find_last_of('.');
string label_left = left.substr(pos_label_lef... | Your typedef doesn't create a new type. It just creates a new name to refer to the same type as before. Thus, when you use < inside your operator function on two strings, the compiler just uses the same operator it's compiling because the argument types match.
What you may wish to do instead is define an entirely new f... |
2,768,282 | 2,768,318 | How to implement fluent interface with a base class, in C++ | How can I implement this fluent interface in C++:
class Base {
public:
Base& add(int x) {
return *this;
}
}
class Derived : public Base {
public:
Derived& minus(int x) {
return *this;
}
}
Derived d;
d.add(1).minus(2).add(3).minus(4);
Current code doesn't work since Base class doesn't know anything ab... | Make Base class templated. Use the wanted return type of Base the template type, like this:
template <typename T>
class Base {
public:
T& add(int x) {
return *static_cast<T *>(this);
}
}
Then inherit Derived from Base like this:
class Derived : public Base<Derived>
Alternatively (as an answer to Noah's comme... |
2,768,328 | 2,768,358 | cleaning up noise in an edge detection algorithm | I recently wrote an extremely basic edge detection algorithm that works on an array of chars. The program was meant to detect the edges of blobs of a single particular value on the array and worked by simply looking left, right, up and down on the array element and checking if one of those values is not the same as the... | Normally in image processing a median filter.
You also often do a dilate (make lines bigger) than an erode (make lines thinner) to close up any gaps in the lines
|
2,768,508 | 2,768,574 | Detect if class has overloaded function fails on Comeau compiler | I'm trying to use SFINAE to detect if a class has an overloaded member function that takes a certain type. The code I have seems to work correctly in Visual Studio and GCC, but does not compile using the Comeau online compiler.
Here is the code I'm using:
#include <stdio.h>
//Comeau doesnt' have boost, so define our ... | I suspect the problem is that as TestClass overloads Func and the Comeau compiler is unable to disambiguate &TestClass::Func, even it it should.
|
2,768,723 | 2,768,756 | Using member functions of members in the constructor initializer | I've run into the following a few times with initializer lists and I've never been able to explain it well. Can anyone explain why exactly the following fails (I don't have a compiler to catch typos, so bear with me):
class Foo
{
public:
Foo( int i ) : m_i( i ) {} //works with no problem
int getInt() {return m_... | The order of initialization is independent of the order of the elements in the initialization list. The actual order is that of the members in the class definition. That is, in your example m_foo will be initialized before m_myInt not because of the initialization list, but because the member appears first in the class... |
2,769,174 | 2,769,222 | Determining if an unordered vector<T> has all unique elements | Profiling my cpu-bound code has suggested I that spend a long time checking to see if a container contains completely unique elements. Assuming that I have some large container of unsorted elements (with < and = defined), I have two ideas on how this might be done:
The first using a set:
template <class T>
bool is_uniq... | Your first example should be O(N log N) as set takes log N time for each insertion. I don't think a faster O is possible.
The second example is obviously O(N^2). The coefficient and memory usage are low, so it might be faster (or even the fastest) in some cases.
It depends what T is, but for generic performance, I'd re... |
2,769,320 | 3,582,347 | vss intializefor backup fails with return code E_UNEXPECTED | #include "vss.h"
#include "vswriter.h"
#include <VsBackup.h>
#include <stdio.h>
#define CHECK_PRINT(result) printf("%s\n",result==S_OK?"S_OK":"error")
int main(int argc, char* argv[])
{
BSTR xml;
LPTSTR errorText;
IVssBackupComponents *VssHandle;
HRESULT result = CreateVssBackupComponents(&VssHandle);
CHECK_PR... | You need to initialize the COM library with the CoInitialize function.
HRESULT result = CoInitialize(NULL);
CHECK_PRINT(result);
result = CreateVssBackupComponents(&VssHandle);
CHECK_PRINT(result);
result = VssHandle->InitializeForBackup();
CHECK_PRINT(result);
This will give you all S_OKs
|
2,769,588 | 2,769,659 | How to free static member variable in C++? | Can anybody explain how to free memory of a static member Variable? In my understanding it can only be freed if all the instances of the class are destroyed. I am a little bit helpless at this point...
Some Code to explain it:
class ball
{
private:
static SDL_Surface *ball_image;
};
//FIXME: how to free static ... | From the sound of it, you don't really want a pointer at all. In fact, since this is coming from a factory function in a C library, it isn't really a "first-class" C++ pointer. For example, you can't safely delete it.
The real problem (if there is one) is to call SDL_FreeSurface on it before the program exits.
This req... |
2,769,768 | 2,769,930 | When is ¦ not equal to ¦? | Background. I'm working with netlists, and in general, people specify different hierarchies by using /. However, it's not illegal to actually use a / as a part of an instance name.
For example, X1/X2/X3/X4 might refer to instance X4 inside another instance named X1/X2/X3. Or it might refer an instance named X3/X4 in... | As I understand it, modern versions of TCL use UTF-8 internally for string representation. In UTF-8, decimal 166 is half of a character, so it's no wonder that all hell is breaking loose. ;-)
My guess is that your C++ code is using a Latin-1 string (i.e., char *) and you're passing that to TCL which is interpreting it... |
2,769,814 | 2,769,889 | How do I use try...catch to catch floating point errors? | I'm using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program.
Because they are random, the trees often generate: divide by zero, overflow, underflow as well as returning "inf" and other strings. I can write handlers for the strings, but the literature left me... | Are you sure you want to catch them instead of just ignoring them? Assuming you just want to ignore them:
See this:
http://msdn.microsoft.com/en-us/library/c9676k6h.aspx
For the _MCW_EM mask, clearing the mask sets the exception, which allows the hardware exception; setting the mask hides the exception.
So you're going... |
2,769,860 | 2,769,872 | Code coordinates to match compass bearings | Right now in Matlab (0,0) is the origin, 0 degrees / 2pi would be to the right of the cartesian plane and angles are measured counter clockwise with 90 degrees being at the top.
I'm trying to write a simulator where the coordinates would match a compass bearing. 0/360 degrees or 2pi would be at the top and 90 degrees ... | You need do nothing more than swap x and y coordinates. This is a reflection in the line x=y. No need to use a matrix or anything. Just swap coordinates before using them. If you really insist on applying a matrix then
[0 1]
[1 0]
swaps x and y.
|
2,769,990 | 2,770,007 | Invalid function declaration. DevC++ | Why do I get invalid function declaration when I compile the code in DevC++ in Windows, but when I compile it in CodeBlocks on Linux it works fine.
#include <iostream>
#include <vector>
using namespace std;
//structure to hold item information
struct item{
string name;
double price;
};
//define sandwich, ch... | You're missing an assignment operator there:
struct item sandwich = {"Sandwich", 3.00};
Note that this is a C syntax though. You probably want to say
item sandwich("Sandwich", 3.00);
and add to item a constructor that takes a string and a double.
|
2,770,104 | 2,770,277 | C++ IO with Hard Drive | I was wondering if there was any kind of portable (Mac&Windows) method of reading and writing to the hard drive which goes beyond iostream.h, in particular features like getting a list of all the files in a folder, moving files around, etc.
I was hoping that there would be something like SDL around, but so far I haven'... | There is no native C++ way to traverse a directory structure or list files in a directory in a cross-platform manner. It's just not built into the language. (For good reason!)
Your best bet is to go with a code framework, and there are a plethora of good options out there.
Boost Filesystem
Apache Portable Runtime
Aaaan... |
2,770,237 | 2,770,261 | Visual Studio 2005 C++ Application Wants To Run As Admin | I wrote a simple c++ application in Visual Studio 2005 but when I compile it, the executable wants to run as admin. I tried deleting the manifest but it still wants to run as admin. I am running Windows Vista Home premium. Any help would be appreciated!
| Windows will ask you for the administrator password if the name of your executable "looks like" a name of a setup program. Name you executable setup.exe and you will be prompted for password every time you run it. What is the name of your executable?
|
2,770,355 | 2,770,987 | Implementing Operator Overloading with Logarithms in C++ | I'm having some issues with implementing a logarithm class with operator overloading in C++.
My first goal is how I would implement the changeBase method, I've been having a tough time wrapping my head around it.
I have tried to understand the math behind changing the base of a logarithm, but i haven't been able to. C... | A few things
Using an _ in the front of your class is a Very Bad Idea (tm). From the c++ standard:
17.4.3.2.1 Global names [lib.global.names]
Certain sets of names and function signatures are always reserved to the
implementation:
Each name that contains a double underscore (_ _) or begins with
an underscore ... |
2,770,428 | 2,770,459 | Calculating depth and descendants of tree | Can you guys help me with the algorithm to do these things? I have preorder, inorder, and postorder implemented, and I am given the hint to traverse the tree with one of these orders. I am using dotty to label (or "visit") the nodes.
Depth is the number of edges from the root to the bottom leaf, so everytime I move, I ... | depth(tree) = 1+ max(depth(tree.left), depth(tree.right));
descendants(tree) = descendants(tree.left) + descendants(tree.right);
For either, returning 0 for a null pointer would end the recursion.
|
2,770,464 | 2,770,478 | c++ vector.push_back error: request for member 'push_back'..., which is of non-class type 'vector(char, allocator(char)) ()()' | I'm using Cygwin with GCC, and ultimately I want to read in a file of characters into a vector of characters, and using this code
#include <fstream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[] )
{
vector<char> string1();
string1.push_back('a');
return 0;
}
... | Don't use parentheses to invoke the default constructor:
vector<char> string1;
Otherwise this declares a function string1 that takes no argumentes and returns a vector<char>.
|
2,770,474 | 2,770,496 | How to find the length of a parameter pack? | Suppose I have a variadic template function like
template<typename... Args>
unsigned length(Args... args);
How do I find the length of the parameter list using the length function ?
| Use sizeof...:
template<typename... Args>
constexpr std::size_t length(Args...)
{
return sizeof...(Args);
}
Note you shouldn't be using unsigned, but std::size_t (defined in <cstddef>). Also, the function should be a constant expression.
Without using sizeof...:
namespace detail
{
template<typename T>
con... |
2,770,555 | 2,770,759 | how do i save time to a file? | i have a program that saves data to file and i want to put a time stamp of the current date/time on that log but when i try to write the time to the file it will not show up but the other data i write will.
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <sstream>
#include <direct... | This is how I'd do it, with a helper function that just gave you the date and time in your desired format for inclusion into any output stream:
#include <time.h>
#include <iostream>
#include <fstream>
using namespace std;
// Helper function for textual date and time.
// DTTMSZ must allow extra character for the null t... |
2,770,745 | 2,770,786 | operator overloading(friend and member function) | What is the difference between operator overloading using the friend keyword and as a member function inside a class?
Also, what is the difference in the case of any unary operator overloading (i.e. as a friend vs. as a member function)?
| Jacob is correct… a friend function declared within a class has access to that class, but it's not inside the class at all, and everyone else has access to it.
For an operator overload which is not a member of the class (also called a free function, it may be a friend, or maybe not), the arguments are the same as the o... |
2,770,855 | 2,770,872 | How do you scale a CBitmap object? | I've loaded a CBitmap object from a resource ID, and I'm now wanting to scale it to 50% its size in each dimension. How might I go about this?
|
Select your CBitmap obj into a memDC A (using CDC::SelectObject())
Create a new CBitmap with desired sized and select it into another MemDC B
Use CDC::stretchblt(...) to stretch bmp in MemDC A into MemDC B
Deselect your CBitmap objects (by selecting what was returned from the previous calls to SelectObject)
Use your ... |
2,770,874 | 2,770,913 | Setting the pixel format of an existing Bitmap in GDI+ | How do I set the PixelFormat property in a GDI+ Bitmap if I can't use one of the constructors that allow me to specify it? It looks like the PixelFormat property itself is read-only.
| I ended up using the following method of creating a second bitmap with the desired pixel format and drawing the original image on to it.
Bitmap *pTempBitmap = new Gdiplus::Bitmap(_Module.m_hInst, MAKEINTRESOURCE(lImageResource));
m_pGDIBitmap = new Bitmap(pTempBitmap->GetWidth(), pTempBitmap->GetHeight(), PixelFormat32... |
2,771,016 | 2,773,213 | Why is there a sizeof... operator in C++0x? | I saw that @GMan implemented a version of sizeof... for variadic templates which (as far as I can tell) is equivalent to the built in sizeof.... Doesn't this go against the second design principle: prefer libraries to language extensions?
| From Variadic Templates (Revision 3)
(N2080=06-0150), page 6:
Although not strictly necessary (we can implement count without this feature), checking the length of a parameter pack is a common operation that deserves a simple syntax. Moreover, this operation may become necessary for type-checking reasons when variadic... |
2,771,023 | 2,771,041 | C99 strict aliasing rules in C++ (GCC) | As far as I understand, GCC supports all of its C99 features in C++. But how is C99 strict aliasing handled in C++ code?
I know that casting with C casts between unrelated types is not strict-aliasing-safe and may generate incorrect code, but what about C++? Since strict aliasing is not part of C++ standard (is that co... | No, you are probably mixing different things.
Strict aliasing rules have absolutely nothing to do with C99 standard specifically. Strict aliasing rules are rooted in parts of the standard that were present in C and C++ since the beginning of [standardized] times. The clause that prohibits accessing object of one type t... |
2,771,312 | 2,771,347 | Struct Array Initialization and String Literals | Is following array initialization correct? I guess it is, but i'm not really sure if i can use const char* or if i better should use std::string. Beside the first question, do the char pointers point to memory segments of same sizes?
struct qinfo
{
const char* name;
int nr;
};
qinfo queues[] = {
{"QALARM", ... | Yes, that looks fine. Obviously you won't be able to subsequently modify any of the name strings (although you can change the pointers to point at different strings if you need to). Storage for each of the const strings will be only as much as is needed and will typically be read-only.
|
2,771,494 | 2,771,507 | how can i diagnose exception in window 7 release mode compilation with VC 2008 | i have strange problem , my application (exe) is working fine in debug mode in windows 7
but stop to work with exception when compiling in release mode .
how can i debug the program to find what is causing the exception this is application with more then 300,000 lines of code ..
| Compile in Release mode but create the .pdb files: How to generate PDB’s for .net managed projects in release mode?
Deploy the .pdb files to same folder as the .exe.
Then attach to process.
|
2,771,515 | 2,771,565 | How to lock file in Windows? | How to lock file in Windows so that this file can be opened/read/wrote only by one process?
I found out that file can be locked with CreateFile by giving 0 to dwShareMode flag. It works but only the returned handle can be used to work with file. But I want to be able to lock the file to other processes and at the same ... | Why do you need to create same file twice in the same process? You could use one handle in all I/O functions of your process without reopening file. If you need to pass the handle to another process you could use DuplicateHandle function.
|
2,771,567 | 2,771,755 | Why exactly is calling the destructor for the second time undefined behavior in C++? | As mentioned in this answer simply calling the destructor for the second time is already undefined behavior 12.4/14(3.8).
For example:
class Class {
public:
~Class() {}
};
// somewhere in code:
{
Class* object = new Class();
object->~Class();
delete object; // UB because at this point the destructor cal... | Destructors are not regular functions. Calling one doesn't call one function, it calls many functions. Its the magic of destructors. While you have provided a trivial destructor with the sole intent of making it hard to show how it might break, you have failed to demonstrate what the other functions that get called ... |
2,771,825 | 2,772,091 | Is undefined behavior worth it? | Many bad things happened and continue to happen (or not, who knows, anything can happen) due to undefined behavior. I understand that this was introduced to leave some wiggle-room for compilers to optimize, and maybe also to make C++ easier to port to different platforms and architectures. However the problems caused b... | I think the heart of the concern comes from the C/C++ philosophy of speed above all.
These languages were created at a time when raw power was sparse and you needed to get all the optimizations you could just to have something usable.
Specifying how to deal with UB would mean detecting it in the first place and then of... |
2,772,190 | 2,772,223 | map operator [] operands | Hi all I have the following in a member function
int tt = 6;
vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt];
set<int>& egressCandidateStops = temp.at(dest);
and the following declaration of a member variable
map<int, vector<set<int>>> m_egressCandidatesByDestAndOtMode;
However I get an error when c... |
operand types are: const std::map< int …
map::operator[] does not work with a const map.
I answered this a few days ago.
map::operator[] is a little odd. It
does this:
Look for the key.
If found, return it.
If not, insert it and default-construct its associated
value.
Then return a reference to the new value.
... |
2,772,310 | 2,772,712 | Simple socket server for Linux | I want TCP/IP based socket server application or code for Linux, which performs a very simple operation: reads xml string from one of the connected socket clients and forwards it to all socket clients which are connected to it.
I have such client server application developed in cocoa, but according to my requirements n... | This is the best free tutorial on the net for linux/unix socket programming in C.
https://beej.us/guide/bgnet/html/multi/index.html
It has example code.
If you want to get serious, buy the Unix Network Programming books by W. Richard Stevens.
I've also done sockets in Java, and they're really easy. Not to mention that ... |
2,772,627 | 2,772,693 | Force the use of interface instead of concrete implementation in declaration (.NET) | In C++, you can do the following:
class base_class
{
public:
virtual void do_something() = 0;
};
class derived_class : public base_class
{
private:
virtual void do_something()
{
std::cout << "do_something() called";
}
};
The derived_class overrides the method do_something() and makes it priva... | If you explicitly implement an interface, this will at least encourage people to use the interface type in the declaration.
interface IMyInterface
{
void MyMethod();
}
class MyImplementation : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
One will only see MyMethod after casting the instance to IM... |
2,772,654 | 2,772,683 | Compiler installation which is simple | Is there any compiler for C++ that works under W7 and is easy to install, except VC++?
I never get these scripts and linux emulations to work, and really just want to try another compiler.
| The nuwen distribultion of the GCC compiler includes the compiler and all necessary supporting tools and libraries as a single Windows installer. You don't need any Linux emulation in order to use it. A similar, slightly smaller pacakage is TDM's MinGW build. Both of these are on GCC 4.5 (as of Aug-2010).
If you want a... |
2,772,742 | 2,774,236 | <hash_set> equality operator doesn't work in VS2010 | Sample code:
std::hash_set<int> hs1; // also i try std::unordered_set<int> - same effect
std::hash_set<int> hs2;
hs1.insert(15);
hs1.insert(20);
hs2.insert(20);
hs2.insert(15);
assert(hs1 == hs2);
hash_set doesn't stores elements in some order defined by hash function... why?
Please note that this code works in VS... | It looks like equality comparisons are broken for both hash_set and unordered_set in Visual C++ 2010.
I implemented a naive equality function for unordered containers using the language from the standard quoted by Matthieu to verify that it's a bug (just to be sure):
template <typename UnorderedContainer>
bool are_equa... |
2,772,746 | 2,772,756 | calling constructor of the class in the destructor of the same class | Experts !! I know this question is one of the lousy one , but still I dared to open my mind , hoping I would learn from all.
I was trying some examples as part of my routine and did this horrible thing, I called the constructor of the class from destructor of the same class.
I don't really know if this is ever required... | When the following runs
test();
you construct a temporary (new) object that is immediately destroyed when control "passes by the semicolon", the destructor for that temporary object is invoked, which constructs another temporary object, etc., so you get a death spiral of endless recursive calls which leads to a stack ... |
2,772,817 | 2,774,607 | How do I optimize this postfix expression tree for speed? | Thanks to the help I received in this post:
I have a nice, concise recursive function to traverse a tree in postfix order:
deque <char*> d;
void Node::postfix()
{
if (left != __nullptr) { left->postfix(); }
if (right != __nullptr) { right->postfix(); }
d.push_front(cargo);
return;
};
This is an expre... | Assuming that processing a cargo is expensive enough that locking a mutex is relatively cheap, you can use a separate thread to access the queue as you put items on it.
Thread 1 would execute your current logic, but it would lock the queue's mutex before adding an item and unlock it afterwards.
Then thread 2 would just... |
2,773,488 | 2,773,716 | Socket Performance C++ Or C# | I have to write an application that is essentially a proxy server to handle all HTTP and HTTPS requests from our server (web browsing, etc). I know very little C++ and am very comfortable writing the application features in C#.
I have experimented with the proxy from Mentalis (C# socket proxy) which seems to work fine ... | How you actually design and code the application is going to make infinitely more of a difference than the platform you choose.
If you design the server efficiently, it will be efficient. If you design it inefficiently, it will be inefficient. There's no clear advantage to choosing C++ over C# or vice versa... unless... |
2,773,629 | 2,773,701 | Simple CArray questions | 1.) What is the difference between
CArray <SomeClass> collection;
and
CArray <SomeClass,SomeClass> collection;
or even
CArray <SomeClass* ,SomeClass* > collection;
?
2.) While reading some comments on Stackoverflow I came to a note saying "Don't use CArray". Why should CArray not be used?
| This:
CArray <SomeClass> collection;
is equivalent to this:
CArray <SomeClass, const SomeClass&> collection;
The second template parameter is used to specify the type through which members are accessed. The template parameters are described in the documentation on MSDN.
This:
CArray <SomeClass* ,SomeClass* > collect... |
2,773,650 | 2,774,138 | Can I do Android Programming in C++, C? | Can I do Android programming in C++, C? If the answer is "yes" then please tell how? And what's the procedure to set up?
I don't know Obj-C, Java, but well-versed in C, C++, Flash AS3, SDK released by Google.
Please do not tell about NVDIA SDK it's not fully developed :)
| PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.
You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.
The standard NDK does not support RTTI and a lot of the functionality of s... |
2,773,927 | 2,773,966 | Using memset on structures in C++ | I am working on fixing older code for my job. It is currently written in C++. They converted static allocation to dynamic but didn't edit the memsets/memcmp/memcpy. This is my first programming internship so bare with my newbe-like question.
The following code is in C, but I want to have it in C++ ( I read that malloc ... | Yes, but only if foo is a POD. If it's got virtual functions or anything else remotely C++ish, don't use memset on it since it'll stomp all over the internals of the struct/class.
What you probably want to do instead of memset is give foo a constructor to explicitly initialise its members.
If you want to use new, don't... |
2,773,977 | 2,774,014 | Convert from float to QByteArray | Is there a quick way to convert a float value to a byte wise (hex) representation in a QByteArray?
Have done similar with memcpy() before using arrays, but this doesn't seem to work too well with QByteArray.
For example:
memcpy(&byteArrayData,&floatData,sizeof(float));
Can go the other way just fine using:
float *val... | From the QByteArray Class Reference page:
float f = 0.0f;
QByteArray array(reinterpret_cast<const char*>(&f), sizeof(f));
Will initialize a QByteArray with the memory content of the float stored in it.
If you already have one and just want to append the data to it:
array.append(reinterpret_cast<const char*>(&f), sizeo... |
2,774,130 | 2,775,036 | Increase the TCP receive window for a specific socket | How to increase the TCP receive window for a specific socket?
- I know how to do so for all the sockets by setting the registry key TcpWindowSize,
but how do do that for a specific one?
According to MSFT's documents, the way is
Calling the Windows Sockets function
setsockopt, which sets the receive
window on a p... | SO_MAX_MSG_SIZE is for UDP. Here's from MSDN:
SO_MAX_MSG_SIZE - Returns the maximum outbound message size for message-oriented sockets supported by the protocol. Has no meaning for stream-oriented sockets.
It's also not settable.
For TCP just use SO_(SND|RCV)BUF.
|
2,774,436 | 2,774,513 | vim + c++: insert a uuid in a guard clause | I'm trying to automate file comment headers. I'm stuck trying to figure out how to insert the result of the uuidgen command into my header using vim's autocmd.
Inside the header, the placeholder text is present, like this:
#ifndef _UUID_
#define _UUID_
// Code goes here!
#endif // _UUID_
The autocmd line to populate... | Use system(), and don't forget to chomp the result
-> matchstr(system('uuidgen'), "[^\n\r]*")
NB: For more complex templates, you could use solutions like mu-template. For instance, in c-header.template, you'd have had to change the value of s:guard to the call to matchtr()+system().
|
2,774,505 | 2,774,612 | How to check the type name of an object in derived classes? | This is my code:
class Base { /* something */ };
class Derived : public Base { /* something */ };
vector<Base*> v; // somebody else initializes it, somewhere
int counter = 0;
for (vector<Base*>::iterator i=v.begin(); i!=v.end(); ++i) {
if (typeof(*i) == "Derived") { // this line is NOT correct
counter++;
}
}
c... | The names of typeid are implementation-defined and you shouldn't make assumptions about them. However, you could compare two typeid's.
if typeid(**i) == typeid(Derived)
Generally it would be considered a bad design (but if the purpose is just to write a not very practical program to count instances of Derived, it's ju... |
2,774,567 | 2,774,920 | QT qmake lowercases my custom widget names | I'm using QT 4.6 on Linux and Windows, and on Linux, it insists on including my QScrollPane by qscrollpane.h
App.pro:
HEADERS += widgets/QScrollPane.h
The section from mainform.ui
<widget class="QScrollPane" name="ListView">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>500</width>
<heig... | You need to provide more info about your custom widget. Add the following to your mainform.ui:
<customwidgets>
<customwidget>
<class>QScrollPane</class>
<extends>QWidget or whatever class is QScrollPane parent</extends>
<header>QScrollPane.h</header>
</customwidget>
</customwidgets>
Should do the trick (discla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.