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.
template< typename T >
int num_allocated_items( T *p )
{
return *((int*)p-4)/sizeof(T);
}
//test
#include <iostream>
int main( int argc, char *argv[] )
{
using std::cout; using std::endl;
typedef long double testtype;
testtype *p = new testtype[ 45 ];
//prints 45
std::cout<<"num allocated = "<<num_allocated_items<testtype>(p)<<std::endl;
delete[] p;
return 0;
}
I'd like to know just how portable this code is.
| 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 example:
class Sandbox
{
public:
void play(Message* m)
{
// call doBuildSandCastle
// or doDigHole based on m's type
}
void doBuildSandCastle();
void doDigHole();
};
Sorry I wasn't clear before.
EDIT:
can someone just delete this train wreck of a question? I really don't want all these highschool lessons in polymorphism.
| 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* handler,MessageType* self)
{
dynamic_cast<MessageHandler<MessageType>&>(*handler).process(self);
}
};
class Message1:
public MessageBase
{
void dispatch(MessageHandlerBase* handler)
{
dynamicDispatch(handler,this);
}
};
Except without having to use dynamic_cast, or passing the message itself (a la the code in the original question.)
|
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, i.e.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
system headers.
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
|
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.c_str());
return 0;
}
I have another cpp file, and I would like to execute the stuff inside the above file. Here is the code for the other file:
HRESULT CButtonDemoBHO::onDocumentComplete(IDispatch *pDisp, VARIANT *vUrl){
ATLTRACE("CButtonDemoBHO::onDocumentComplete %S\n", vUrl->bstrVal);
// <---- i would like to call funtionHTML here or ..
if (isMainFrame(pDisp)){
m_normalPageLoad=false;
// <---- here..
MessageBox(m_hWnd, L"Main Document has completed loading", L"Document Complete", MB_OK);
return S_OK;
}
return S_OK;
}
I got the error C2065: 'url' : undeclared identifier.
Need help.
| 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 url in the scope in which you are attempting to make that invocation; you need to create your own variable of type const wchar_t* to use as a parameter to functionHtml().
|
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 repurpose to indicate mutable state.
Edit: Since the intent of this was mistaken entirely (and since I wasn't around for a few hours to clarify), let me explain. In essence, I just want to know what systems are available for manipulating the type system at compile time. I don't care if this creates nonstandard, bad, unmaintainable, useless code. I'm not going to use it in production. It's just a curiosity.
Potential (suboptimal) solutions so far:
// I presume redefinition of keywords is implementation-defined or illegal.
#define int int const
#define ptr * const
int i(0);
int ptr j(&i);
typedef int const Int;
typedef int const* const Intp;
Int i(0);
Intp j(&i);
template<class T>
struct C { typedef T const type; typedef T const* const ptr; };
C<int>::type i(0);
C<int>::ptr j(&i);
| 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 readability gains from immutable types - just look at most functional languages.
|
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 program:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
...
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
|
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 files, I don't get error and 0 is printed instead of 5.
Please explain the reason.
Moreover I want to ask whether we need to declare a function before defining it because
I haven't declared it in file1.cpp but no error comes in compilation.
| 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 will merrily use this when fun(double) is called.
C++ on the other hand mangles the assembly names, so you'll get something like _fun@int for fun(int) and _fun@double for fun(double), in order for overloading to work. The linker will see these have different names and spurt out an error that it can't find the definition for fun(double).
For your second question it is always a good idea to declare function prototypes, generally done in a header, especially if the function is used in multiple files. There should be a warning option for missing prototypes in your compiler, gcc uses -Wmissing-prototypes. Your code would be better if set up like
// file1.hpp
#ifndef FILE1_HPP
#define FILE1_HPP
void fun(int)
#endif
// file1.c
#include "file1.hpp"
...
// file2.c
#include "file1.hpp"
int main()
{
fun(5);
}
You'd then not have multiple conflicting prototypes in your program.
|
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
#endif // TEST_GLOBAL_H
Why this file is generated, how I suppose to use it?
Thanks.
| 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", and when you use your dll in some application, the header will have "Q_DECL_IMPORT" macro.
For more information, check the Qt documentation.
|
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 the call? As I see it the result will depend on whether the base class destructor can be called twice without invoking erroneous behavior.
For example in this case:
class BaseSafe {
public:
~BaseSafe()
{
}
private:
int data;
};
class DerivedSafe {
public:
~DerivedSafe()
{
BaseSafe::~BaseSafe();
}
};
everything will be fine - the BaseSafe destructor can be called twice safely and the program will run allright.
But in this case:
class BaseUnsafe {
public:
BaseUnsafe()
{
buffer = new char[100];
}
~BaseUnsafe ()
{
delete[] buffer;
}
private:
char* buffer;
};
class DerivedUnsafe {
public:
~DerivedUnsafe ()
{
BaseUnsafe::~BaseUnsafe();
}
};
the explicic call will run fine, but then the implicit (automagic) call to the destructor will trigger double-delete and undefined behavior.
Looks like it is easy to avoid the UB in the second case. Just set buffer to null pointer after delete[].
But will this help? I mean the destructor is expected to only be run once on a fully constructed object, so the optimizer could decide that setting buffer to null pointer makes no sense and eliminate that code exposing the program to double-delete.
Is the compiler allowed to do that?
| 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 after calling the destructor.
But even if the setting of the buffer to null wasn't removed by the compiler, it seems like calling the destructor twice would result in UB.
|
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]; }
int& operator[]( int index );
IntArray& operator =( const IntArray& rightside );
~IntArray() { delete [] a; }
private:
int *a;
int size;
int used;//for array position
};
int main()
{
IntArray copy;
if( 2>1)
{
IntArray arr(5);
for( int k=0; k<5; k++)
arr[k]=k;
copy = arr;
for( int j=0; j<5; j++)
cout<<arr[j];
}
cout<<" ";
for( int j=0; j<5; j++)
cout<<copy[j];
return 0;
}
int& IntArray::operator[]( int index )
{
if( index >= size )
cout<<"ilegal index in IntArray"<<endl;
return a[index];
}
IntArray& IntArray::operator =( const IntArray& rightside )
{
if( size != rightside.size )//also checks if on both side same object
{
delete [] a;
a= new int[rightside.size];
}
size=rightside.size;
used=rightside.used;
for( int i = 0; i < used; i++ )
a[i]=rightside.a[i];
return *this;
}
| 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 case) need to supply a copy-constructor as well.
|
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;
CString headers;// = APPLICATION_SUITE_NAME;
DWORD dwHeadersLength = -1;
headers.Format("%s %s %s\n",APPLICATION_SUITE_NAME,SHORT_APPLICATION_VERSION,BUILDNO_STR);
pHttpFile =(CHttpFile *) internet.OpenURL(lpszURL, 1, INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_DONT_CACHE, headers, dwHeadersLength);
Without the headers, dwHeadersLength parameter (eg. pass in NULL,-1) then it goes through fine and I see the request come through to our website. But why does it fail if I pass in custom headers?
| 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 that lpszHeaders
is zero-terminated (ASCIIZ), and the
length is calculated. If
HttpSendRequestW is called, the
function fails with
ERROR_INVALID_PARAMETER.
I'm mentioning HttpSendRequest() because, in fact, CInternetSession::OpenURL() calls InternetOpenUrl(), whose documentation for the lpszHeaders parameters sends you to the doc page for HttpSendRequest().
EDIT: Another possibility is that the call fails because the headers do not seem to be in canonical format: according to the HTTP 1.1 spec, they ought to be in "name: value" format, and each header should be separated from the next one by CRLF.
|
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-constructible) you will want declval which is a function that takes a type and returns a meaningless, invalid value of that type. declval can only be used in unevaluated contexts such as decltype.
typedef typename decltype( std::declval<T>().toCPD() ) D;
Before C++11, decltype was a non-standard extension by Microsoft's MSVC compiler. Its behavior might have been changed slightly by standardization.
typeof is GCC's equivalent pre-C++11 extension like decltype, which was also cloned in other compilers. Here is its documentation from GCC. That page provides no comparison between the features, but it notes that typeof must be called __typeof__ when using a standard mode (-std=c++YY, which you should always do), and it is available in C as well as C++.
For the sake of C compatibility, __typeof__ will not resolve a reference type from a glvalue expression. So, it's really only suitable for C. This probably explains why the C++ feature didn't inherit the more self-explanatory name: GNU was unwilling to sacrifice backward compatibility, whereas Microsoft cares less about C and perhaps needed fewer changes.
result_of is a C++11 metafunction (previously standardized in the ISO TR1 library from 2006). It is a template which takes a callable type (such as a function int(void), function pointer int(*)(void), functor class implementing operator(), or pointer-to-member-function &T::toCPD) and an argument type-list for that type, and provides the return type if the call would work.
To use result_of with a pointer to member function, you must include the parent object type in the argument list as a surrogate for this.
typedef typename std::result_of< decltype( & T::toCPD ) ( T * ) >::type D;
This is very brittle, though, because &T::toCPD cannot be resolved if there's any overloading, such as a non-const version. This is true despite the fact that T * or T const * must be explicitly written out! In most cases, you're better off with decltype and declval.
|
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 goToWork() {return false;}
template<WeekDay DAY>
typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;}
source:
bool b = goToWork<MONDAY>();
compiler this gives
error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY!=6,bool>::type goToWork(void)'
and
error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY==6,bool>::type goToWork(void)'
But if I change the function template parameter from the enum type WeekDay to int, it compiles fine:
template<int DAY>
typename enable_if_c< DAY==SUNDAY, bool >::type goToWork() {return false;}
template<int DAY>
typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;}
Also the normal function template specialization works fine, no surprises there:
template<WeekDay DAY> bool goToWork() {return true;}
template<> bool goToWork<SUNDAY>() {return false;}
To make things even weirder, if I change the source file to use any other WeekDay than MONDAY or TUESDAY, i.e. bool b = goToWork<THURSDAY>(); the error changes to this:
error C2440: 'specialization' : cannot convert from 'int' to 'const WeekDay'
Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)
EDIT: Maybe someone could test this with a different compiler (other than Visual Studio 2010) to see if the same thing happens, because it doesn't seem to make any sense
EDIT: I found a new "interesting" aspect of this behaviour. That is if I change the direct comparison of the template parameter with == and != operators into a comparison with a helper struct template, it works fine:
template<WeekDay DAY>
struct Is
{
static const bool Sunday = false;
};
template<>
struct Is<SUNDAY>
{
static const bool Sunday = true;
};
template<WeekDay DAY>
typename enable_if_c< Is<DAY>::Sunday, bool >::type goToWork() {return false;}
template<WeekDay DAY>
typename enable_if_c< !Is<DAY>::Sunday, bool >::type goToWork() {return true;}
EDIT:
By the way, I made a bug report and this is the answer from Microsoft: "This is a bug that manifests when attempting to promote the non-type template parameter. Unfortunately, given our resource constraints for this release and that a worked-around is available, we will not be able to fix this in the next release of Visual Studio. The work-around is to change the template parameter type to an int."
(I think "this release" refers to Visual Studio 2010)
| 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 definetely a NOOP, when switched off. I'm wondering, if I have the following code, if a compiler (MSVS / gcc) is able to optimize out the function call, so that it is again a NOOP. (By doing that, the switch could be in the .cpp and switching will be much faster, compile/link time wise).
--Header--
void printDebug(const Basic* p);
class Basic {
Basic() {
simpleSetupCode;
// this should be a NOOP in release,
// but constructor could be inlined
printDebug(this);
}
};
--Source--
// PRINT_DEBUG defined somewhere else or here
#if PRINT_DEBUG
void printDebug(const Basic* p) {
// Lengthy debug print
}
#else
void printDebug(const Basic* p) {}
#endif
| 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 hardcode new instances of these variables into my main code.
My first attempt at creating an array is as follows:
const u8* pl[] = {
&foo,
&bar
};
This gave me the error cannot convert 'const u8 (*)[]' to 'const u8*' in initialization, and with help elsewhere along with some Googling, I changed my array to this:
u8 (*pl)[] = {
&foo,
&bar
};
Upon compiling I now get the error scalar object 'pl' requires one element in initializer.
Does anyone have any ideas on what I'm doing wrong? Thanks.
| 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;
IplImage* maxframe = 0;
While looping the maxframe is found by
if( currentvalue > maxvalue ) {
maxvalue = currentvalue;
maxframe = frame;
}
I'm aware that what I am storing in the maxframe variable is the same pointer to the frame currently loaded in the frame pointer. When a new frame is loaded into the frame variable, this will also be pointed to by the maxframe pointer. So when I save the image pointed to by maxframe, I save the last image in the loop no matter what its calculated value is.
I have tried a lot of different solutions, but I can't seem to solve this problem. Can anyone help me? :)
| 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.clone();
|
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 - like this:
ifstream file1(...);
ofstream file2(...);
std::copy(istream_iterator<char>(file1),istream_iterator<char>(),ostream_iterator<char>(file2));
However that really isn't a copy - it's creating a new file with the same contents. It won't correctly handle hard links or symlinks, it won't correctly handle metadata and it will only 'copy' the default file stream.
If you need a file copy on Windows you should call one of CopyFile, CopyFileEx or CopyFileTransacted depending on your exact requirements.
|
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::stream_protocol::iostream?
| 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 GiantSpaceShip" << endl;
}
};
class ExplodingAsteroid : public Asteroid {
public:
virtual void CollideWith(SpaceShip *) {
cout << "ExplodingAsteroid hit a SpaceShip" << endl;
}
virtual void CollideWith(GiantSpaceShip *) {
cout << "ExplodingAsteroid hit a GiantSpaceShip" << endl;
}
};
int main()
{
SpaceShip * s = new GiantSpaceShip();
Asteroid * a = new ExplodingAsteroid();
a->CollideWith(s);
getch();
return 0;
}
How can I enable double dispatch in C++?
| 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_DELETEONRELEASE,
FILE_ATTRIBUTE_NORMAL,
FALSE,
NULL,
&dataStream);
}
return dataStream;
}
Error: error LNK2019: unresolved external symbol __imp__SHCreateStreamOnFileEx@24 referenced in function "public: void __thiscall replace::GetStream(void)" (?GetStream@replace@@QAEXXZ) replace.obj replace
| 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 symbol "public: __thiscall server_communication::TcpServer::TcpServer(class boost::asio::io_service &,struct server_communication::ServerParameters &)" (??0TcpServer@server_communication@@QAE@AAVio_service@asio@boost@@AAUServerParameters@1@@Z) referenced in function "public: __thiscall server_controller::ServerController::ServerController(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??0ServerController@server_controller@@QAE@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0@Z)
I seems that the symbols can not be found in the other projects, even though there are defined in those projects.
| 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 that you read blocks of data a time from the end, scanning backwards through each block for newline marker, and stitching things back together at block boundaries.
Writing
If the data all fit in memory at once, put the numbers into a list (in Python):
open('foo.txt', 'w').writelines(reversed(data))
If data is an iterable, replace it with list(data).
If the data doesn't fit in memory (e.g., you have some generator that spits out a ton of data), the problem will be much harder. The simplest solution that comes to mind is to just push the data into a sqlite database and then copy it into the file. Or you might just find it easier to use the data directly from sqlite.
|
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; i++) {
things[i] = a[i];
}
}
~Array() {
delete[] things;
}
T& operator [](const int idx) const {
return things[idx];
}
};
int main()
{
int a[] = {1,2,3};
double b[] = {1.2, 3.5, 6.0};
Array<int> intArray(a, 3);
Array<double> doubleArray(b, 3);
cout << "intArray[1]: " << intArray[1] << endl;
}
|
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::SomeClass{
socket_ = new QTcpSocket();
}
SomeClass::~SomeClass{
delete socket_;
}
| 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, 0, LR_DEFAULTSIZE | LR_LOADTRANSPARENT | LR_LOADMAP3DCOLORS );
SendMessage(GetDlgItem(hWndDlg, IDC_MOVEUP),BM_SETIMAGE,(WPARAM)IMAGE_BITMAP,(LPARAM)hbmpUpDisabled);
Does anyone notice any problems here? It works if my bitmap is a 1-bit bitmap. I couldn't get a 32 bit bitmap to work, and I'm not sure how to setup a 24 bit or 8 bit bitmap to do it.... I tried a custom 255,0,255 color (which IIRC is a default transparent value), but so far no joy....
| 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 bitmap with the correct button color in its background areas.
That said - I suspect that some of these restrictions may be lifted for buttons implemented by common controls v6. Add commctl 6 as a dependend assembly to your exe and see if the behaviour changes.
|
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 function than the __inline hint (e.g. inline even if it result in worse code).
There's also __attribute__((always_inline)) in GCC and clang.
|
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) -> bool
{
if(tempsum >= sum)
return true;
tempsum += temp;
sum -= temp;
return false;
});
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)
For example if we would have { 2.4, 0.12, 1.26, 0.51, 0.70 }, the best split would be { 2.4, 0.12 } and { 1.26, 0.51, 0.70 }.
If it helps, I'm trying to achieve the splitting algorithm for the Shannon Fano encoding.
Maybe this will help you guys understand my question better http://en.wikipedia.org/wiki/Shannon%E2%80%93Fano_coding#Example
Any input is appreciated, thanks!
| 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 given (unless I mucked something up ... I didn't actually compile or test it). It also works if you have negative numbers in the original vector:
std::pair<std::vector<double>, std::vector<double> >
split(const std::vector<double>& data)
{
std::pair<std::vector<double>, std::vector<double> > rv;
double s1=0.0, s2=0.0;
std::vector<double>::const_iterator i;
for (i=data.begin(); i != data.end(); ++i)
{
double dif1 = abs(*i + s1 - s2);
double dif2 = abs(*i + s2 - s1);
if (dif1 < dif2)
{
rv.first.push_back(*i);
s1 += *i;
}
else
{
rv.second.push_back(*i);
s2 += *i;
}
}
return rv;
}
EDIT: The quality of the result will be lower with this approach if there the sum of the negative numbers in your vector overwhelms the sum of the positive numbers in the list. To resolve, you could try to order the original list by descending absolute value rather than in strictly descending order.
|
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). In Visual Studio 2008 things seemed to work out okay (might have been a coincidence), but in Visual Studio 2010 the wrong instance of libexpat is linked. I was thinking that if I could specify the order in which these two libraries should be linked that then I could circumvent the problem.
| 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' or something like this) that means "Space" that I can use from standard input for my code?
| 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 suggest using get, like this prior to your loop
cin.get( a, n );
Note: get will stop retrieving chars from the stream if it either finds a newline char (\n) or after n-1 chars. It stops early so that it can append the null character (\0) to the array. You can read more about the istream interface here.
|
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 supported by your implementation either in the std::tr1 or std namespace; you'd have to check.
|
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() {}
virtual ABC * clone() = 0;
};
struct D1 : public ABC
{
virtual D1 * clone() { return new D1( *this ); } // Covariant Return Type
};
A deep copy is then:
for( i = 0; i < oldVector.size(); ++i )
newVector.push_back( oldVector[i]->clone() );
Drawbacks
As Andrei Alexandrescu states it:
The clone() implementation must follow the same pattern in all derived classes; in spite of its repetitive structure, there is no reasonable way to automate defining the clone() member function (beyond macros, that is).
Moreover, clients of ABC can possibly do something bad. (I mean, nothing prevents clients to do something bad, so, it will happen.)
Better design?
My question is: is there another way to make an abstract base class clonable without requiring derived classes to write clone-related code? (Helper class? Templates?)
Following is my context. Hopefully, it will help understanding my question.
I am designing a class hierarchy to perform operations on a class Image:
struct ImgOp
{
virtual ~ImgOp() {}
bool run( Image & ) = 0;
};
Image operations are user-defined: clients of the class hierarchy will implement their own classes derived from ImgOp:
struct CheckImageSize : public ImgOp
{
std::size_t w, h;
bool run( Image &i ) { return w==i.width() && h==i.height(); }
};
struct CheckImageResolution { ... };
struct RotateImage { ... };
...
Multiple operations can be performed sequentially on an image:
bool do_operations( vector< ImgOp* > v, Image &i )
{
for_each( v.begin(), v.end(),
/* bind2nd( mem_fun( &ImgOp::run ), i ... ) don't remember syntax */ );
}
If there are multiple images, the set can be split and shared over several threads. To ensure "thread-safety", each thread must have its own copy of all operation objects contained in v -- v becomes a prototype to be deep copied in each thread.
Edited: The thread-safe version uses the Prototype design pattern to enforce copy of pointed-to-objects -- not ptrs:
struct ImgOp
{
virtual ~ImgOp() {}
bool run( Image & ) = 0;
virtual ImgOp * clone() = 0; // virtual ctor
};
struct CheckImageSize : public ImgOp { /* no clone code */ };
struct CheckImageResolution : public ImgOp { /* no clone code */ };
struct RotateImage : public ImgOp { /* no clone code */ };
bool do_operations( vector< ImgOp* > v, Image &i )
{
// In another thread
vector< ImgOp* > v2;
transform( v.begin(), v.end(), // Copy pointed-to-
back_inserter( v2 ), mem_fun( &ImgOp::clone ) ); // objects
for_each( v.begin(), v.end(),
/* bind2nd( mem_fun( &ImgOp::run ), i ... ) don't remember syntax */ );
}
This has sense when image operation classes are small: do not serialize accesses to unique instances of ImgOps, rather provide each thread with their own copies.
The hard part is to avoid writers of new ImgOp-derived classes to write any clone-related code. (Because this is implementation detail -- this is why I dismissed Paul's answers with the Curiously Recurring Pattern.)
| 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: when ImgOp is copied, copy ctor and
// assignement operator perform a *real* copy of object
ImageOp ( const ImageOp &other ) : m_t( other .m_t ) {}
ImageOp & operator=( const ImageOp & );
public:
ImageOp ( const T &p_t ) : m_t( p_t ) {}
ImageOp<T> * clone() const { return new ImageOp<T>( *this ); }
bool run( Image &i ) const { return m_t.run( i); }
};
// Image operations need not to derive from a base class: they must provide
// a compatible interface
class CheckImageSize { bool run( Image &i ) const {...} };
class CheckImageResolution { bool run( Image &i ) const {...} };
class RotateImage { bool run( Image &i ) const {...} };
Now all the clone-related code lies within a unique class. However, it is now impossible to have a container of ImgOps templatized on different operations:
vector< ImgOp > v; // Compile error, ImgOp is not a type
vector< ImgOp< ImgOp1 > > v; // Only one type of operation :/
Step #2, Add a level of abstraction
Add a non-template base acting as an interface:
class AbstractImgOp
{
ImageOp<T> * clone() const = 0;
bool run( Image &i ) const = 0;
};
template< typename T >
class ImgOp : public AbstractImgOp
{
// No modification, especially on the clone() method thanks to
// the Covariant Return Type mechanism
};
Now we can write:
vector< AbstractImgOp* > v;
But it becomes hard to manipulate image operation objects:
AbstractImgOp *op1 = new AbstractImgOp;
op1->w = ...; // Compile error, AbstractImgOp does not have
op2->h = ...; // member named 'w' or 'h'
CheckImageSize *op1 = new CheckImageSize;
op1->w = ...; // Fine
op1->h = ...;
AbstractImgOp *op1Ptr = op1; // Compile error, CheckImageSize does not derive
// from AbstractImgOp? Confusing
CheckImageSize op1;
op1.w = ...; // Fine
op1.h = ...;
CheckImageResolution op2;
// ...
v.push_back( new ImgOp< CheckImageSize >( op1 ) ); // Confusing!
v.push_back( new ImgOp< CheckImageResolution >( op2 ) ); // Argh
Step #3, Add a "cloning pointer" class
Based on the FredOverflow's solution, make a cloning pointer to make the framework simpler to use.
However, this pointer needs not to be templatized for it is designed to hold only one type of ptr -- only the ctor needs to be templatized:
class ImgOpCloner
{
AbstractImgOp *ptr; // Ptr is mandatory to achieve polymorphic behavior
ImgOpCloner & operator=( const ImgOpCloner & );
public:
template< typename T >
ImgOpCloner( const T &t ) : ptr( new ImgOp< T >( t ) ) {}
ImgOpCloner( const AbstractImgOp &other ) : ptr( other.ptr->clone() ) {}
~ImgOpCloner() { delete ptr; }
AbstractImgOp * operator->() { return ptr; }
AbstractImgOp & operator*() { return *ptr; }
};
Now we can write:
CheckImageSize op1;
op1.w = ...; // Fine
op1.h = ...;
CheckImageResolution op2;
// ...
vector< ImgOpCloner > v;
v.push_back( ImgOpCloner( op1 ) ); // This looks like a smart-ptr, this is not
v.push_back( ImgOpCloner( op2 ) ); // confusing anymore -- and intent is clear
|
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 "FakePort.h"
std::string Port::me() { return "FakePort"; }
main.cpp
#include "Port.h"
int main() {
Port port;
std::cout << "Hello world from " << port.me() << std::endl;
return 0;
}
Building
# g++ -c -o Port.o Port.cpp
# ar rc Port.a Port.o
# g++ -c -o FakePort.o FakePort.cpp
# ar rc FakePort.a FakePort.o
# g++ -c -o main.o main.cpp
# g++ main.o Port.a FakePort.a
# ./a.out
Hello world from Port
Change library order
# g++ main.o FakePort.a Port.a
# ./a.out
Hello world from FakePort
According to this page:
If a symbol is defined in two different libraries gcc will use the first one it finds and ignore the second one unless the second one is included in an object file which gets included for some other reason.
So the above behavior make sense. Unfortunately I am inheriting a sizable code base that doesn't make use of namespaces (and adding them isn't feasible right now) and uses some generic class names throughout multiple libraries. I would like to automatically detect duplicate names at link time to make sure that the wrong copy of a class isn't accidentally being instantiating. Something like:
# g++ -Wl,--warnLibraryDupSymbols main.o FakePort.a Port.a
Warning: Duplicate symbol: Port
but I can't find anything in the GCC linker options to do that. Is it possible to get GCC to automatically detect and report such cases?
| 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 used to turn an archive file into a shared library, forcing every object to be included in the resulting shared library. This option may be used more than once.
I haven't tried it, but it sounds as if it'll pull in all the items in a library as if they were object files. You'll need to specify the option for each library.
As Neil said, this won't give you class-level conflicts, but if there are class members with the same signature, this might make the linker tell you.
|
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.
What's the rationale behind that?
| 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 both integral and floating points behind methods.
It will change with C++0x, so there's hope.
|
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 errors that occur with sockets in windows.
So I was wondering if anyone was aware of a way to replace this function in standard c++?
A way to get different error numbers for different outcomes of connecting/dissconecting a socket would be sufficent.
| 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.dwControlKeyState = 0;
tControl_c.dwCtrlWakeupMask = NULL;
pBuf[0] = 0x00;
do
{
ReadConsole( hConsole_c, pStr, (*pBufLen) * sizeof(TCHAR), pBufLen, &tControl );
}
while ( pStr[0] == 0x00 );
The code executes without throwing an exception. However, when the ReadConsole() function executes the error code ERROR_INVALID_HANDLE (0x06) is flagged. I have verified hConsole_c to be a valid handle. Does anyone have any insight as to what I am doing wrongly? I am using Visual C++ 2008 Express Edition. Thanks.
| 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 context and I have a pretty simple design in mind. However, since things are often more complex than they seem to, I wonder how our C++ gurus would implement this, preferably in an elegant and standard way.
All suggestions are welcome !
| 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 new standard version of boost::function and boost::bind
|
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 through the whole string and when I find a null character i start putting into the second array . But how can I do it without putting it into a variable and traversing .. I mean directly from the file itself ..
| 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 program invoking undefined behaviour should behave. Also known as "nasal demons" because theoretically it could make demons fly out of your nose.
Using undefined behaviour is nearly always a bad idea. Even if it seems to work sometimes, any change to environment, compiler or platform can randomly break your code.
|
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 '=' operator in this case to work with the '[ ]' operator?
| 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'm struck with the next step : create and launch user's rdp-session.
I don't know how to handle this problem without having the Remote Desktop Client Gui.
I'm working on a Windows Server 2003 and I'm using VS2008 with .NET 3.5.
Regards.
| 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(dy>0);
p = new float*[dx];
for (int i = 0; i < dx; i++){
p[i] = new float[dy];
}
}
};
Matrix::Matrix(int sizeX=1, int sizeY=1)
: dx(sizeX),dy(sizeY) {
allocArrays();
for (int i = 0; i < dx; i++) {
for (int j = 0; j < dy; j++) {
p[i][j] = 0;
}
}
}
Matrix::Matrix(const Matrix& m) : dx(m.dx), dy(m.dy) {
allocArrays();
for (int i=0; i<dx; ++i) {
for (int j=0; j<dy; ++j) {
p[i][j] = m.p[i][j];
}
}
}
Matrix::~Matrix() {
for (int i = 0; i < dx; i++) {
delete [] p[i];
}
delete [] p;
p = 0;
}
My main code is:
int main()
{
Matrix myArray[2] = { Matrix(6,6)};
return 0;
}
When I compile with g++ I get the following error:
matrixTesting.cc: In function ‘int main()’:
matrixTesting.cc:197: error: call of overloaded ‘Matrix()’ is ambiguous
matrixTesting.cc:11: note: candidates are: Matrix::Matrix()
matrixTesting.cc:44: note: Matrix::Matrix(int, int)
matrixTesting.cc:197: warning: unused variable ‘myArray’
I did some searching around google but I haven't found an answer. Suppose there is a problem with my constructor.
| 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) ) {
separate.str(row); // = HERE is PROBLEM =
while( getline(separate, strNum, '|') ) { // using delimiter
flNum = strToFl(strNum); // my conversion
insertIntoMatrix(i,j,flNum); // some function
j++;
}
i++;
}
In marked point, row is copied into separate stream only first time. In next iteration it doesn't work and it does nothing. I expected it is possible to be used more times without constructing new istringstream object in every iteration.
| 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 hand, g++ 4.3 gets it right.
what should be correct behavior according to standard?
Meanwhile, I refactor slightly to make problem go away.
| 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 the name of a member of the base class is the same as the name of a template- parameter, the base class name or member name hides the template-parameter name (3.3.7).
|
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* message = someMessage();
message->apply(this); // use polymorphism to determine what function to call.
I have seen many ways to do this which all seem less elegant even then the basic switch statement. Using dyanimc_cast, inheriting from a messageHandler class that needs to be updated every time a new message is added, using a container of function pointers, all seem to defeat the purpose of making code easier to maintain by replacing switches with polymorphism.
This is as close as I can get: (I use templates to avoid inheriting from an all-knowing handler interface)
class Base
{
public:
template<typename T> virtual void apply(T* sandbox) = 0;
};
class Alpha : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyAlpha();
}
};
class Bravo : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyBravo();
}
};
class Sandbox
{
public:
void run()
{
Base* alpha = new Alpha;
Base* bravo = new Bravo;
alpha->apply(this);
bravo->apply(this);
delete alpha;
delete bravo;
}
void applyAlpha() {
// cout << "Applying alpha\n";
}
void applyBravo() {
// cout << "Applying bravo\n";
}
};
Obviously, this doesn't compile but I'm hoping it gets my problem accross.
| 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 MessageBase
{
public:
virtual void dispatch(HandlerBase* handler) = 0;
template<typename MessageType>
void dynamicDispatch(HandlerBase* handler, MessageType* self)
{
dynamic_cast<Handler<MessageType>&>(*handler).process(*self);
}
};
template<typename MessageType> class Message : public MessageBase
{
virtual void dispatch(HandlerBase* handler)
{
dynamicDispatch(handler, static_cast<MessageType*>(this));
}
};
class AlphaMessage : public Message<AlphaMessage>
{
};
class BravoMessage : public Message<BravoMessage>
{
};
class Sandbox : public Handler<AlphaMessage>, public Handler<BravoMessage>
{
public:
void run()
{
MessageBase* alpha = new AlphaMessage;
MessageBase* bravo = new BravoMessage;
alpha->dispatch(this);
bravo->dispatch(this);
delete alpha;
delete bravo;
}
virtual void process(const AlphaMessage&) {
// cout << "Applying alpha\n";
}
virtual void process(const BravoMessage&) {
// cout << "Applying bravo\n";
}
};
int main()
{
Sandbox().run();
return 0;
}
|
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(); // Compiler error: foo() is protected within this context
};
};
I guess I could change it too a->Base::foo() but since foo() is pure virtual in the Base class, the call will result in calling Derived::foo() anyway.
However, the compiler seems to refuse a->foo(). I guess it is logical, but I can't really understand why. Am I missing something ? Can't (shouldn't) it handle this special case ?
Thank you.
| 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 problem is that in C++, friendship is not inherited. If you want Other to have special access to Derived, it needs to be a friend of Derived specifically.
This, on the other hand, works:
Base* a = new Derived();
a->foo();
Because here, you are calling foo() on a Base* where foo() is public, and since you are not qualifying foo() with a class name, it uses dynamic dispatch and ends up calling the Derived version of Foo.
|
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 explained this:
Notice that Y::f(X*) takes the address of an X
object. This is critical because the compiler always knows how to
pass an address, which is of a fixed size regardless of the object
being passed, even if it doesn’t have full information about the size
of the type. If you try to pass the whole object, however, the
compiler must see the entire structure definition of X, to know the
size and how to pass it, before it allows you to declare a function
such as Y::g(X).
But when I tried
void f(X);
as declaration in struct Y, it shows no error.
Please explain why?
| 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<<cargo<<"\n";
return;
};
Now I need to evaluate the values and operators as they are returned. My problem is how to retrieve
them. I tried the std::stack:
#include <stack>
stack <char*> s;
void Node::postfix()
{
if (left != __nullptr) { left->postfix(); }
if (right != __nullptr) { right->postfix(); }
s.push(cargo);
return;
};
but when I tried to access it in main()
while (!s.empty())
{
cout<<s.top<<"\n";
s.pop;
}
I got the error:
'std::stack<_Ty>::top': function call missing argument list; use '&std::stack<_Ty>::top' to create
a pointer to member'
I'm stuck.
Another question to follow shortly.
| 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 = 00;
int minute = 0;
const int ZERO = 00;
do{
while (second <= 59){
if(minute == 5) break;
second += 1;
if(second == 60) minute += 1;
if(second == 60) second = ZERO;
if(second < 60) cout << "Current Time> "<< minute <<" : "<< second <<" \n";
}
} while (minute <= 5);
}
| 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 that are running while your program is executing.
|
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_left);
string label_right = right.substr(pos_label_right);
int last_pos_label_left=0, last_pos_label_right=0;
while(pos_label_left!=string::npos && pos_label_right!=string::npos){
if(label_left<label_right) return true;
else if(label_left>label_right) return false;
else{
last_pos_label_left = pos_label_left;
last_pos_label_right = pos_label_right;
pos_label_left = left.find_last_of('.', last_pos_label_left);
pos_label_right = right.find_last_of('.', last_pos_label_left);
label_left = left.substr(pos_label_left, last_pos_label_left);
label_right = right.substr(pos_label_right, last_pos_label_right);
}
}
}
I know it's a strange way to overload the operator <, but I have to do it this way. It should do what I want. That's not the point.
The problem is that it enter in an infinite loop right in this line:
if(label_left<label_right) return true;
It seems like it's trying to use this overloading function itself to do the comparision, but label_left is a string, not a domain name!
Any suggestion?
| 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 function:
bool domain_less(domain_name const& left, domain_name const& right);
Then use that function in places that call for a comparison function, such as std::sort. Most of the standard algorithms will use < by default, but allow you to provide your own predicate function instead. You may need to use std::ptr_fun to wrap your function. You can also write your own functor object; it's typical to descend from std::binary_function in that case. (Check out the <functional> header.)
|
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 about Derived class, etc. I would be very thankful for a hint/suggestion.
| 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 comment), if you don't want to change Base, you could use an intermediate class that performs the casting, like this:
template <typename T>
class Intermediate : public Base {
public:
T& add(int x) {
Base::add(x);
return *static_cast<T *>(this);
}
}
And let Derived inherit from Intermediate:
class Derived : public Intermediate<Derived>
|
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 value it was currently looking at. The goal was not to produce a mathematical line but rather a set of ordered points that represented a descritized closed loop edge.
The algorithm works perfectly fine, except that my data contained a bit of noise hence would randomly produce edges where there should be no edges. This in turn wreaked havoc on some of my other programs down the line.
There is two types of noise that the data contains. The first type is fairly sparse and somewhat random. The second type is a semi continuous straight line on the x=y axis. I know the source of the first type of noise, its a feature of the data and there is nothing i can do about it. As for the second type, i know it's my program's fault for causing it...though i haven't a hot clue exactly what is causing it.
My question is:
How should I go about removing the noise completely?
I know that the correct data has points that are always beside each other and is very compact and ordered (with no gaps) and is a closed loop or multiple loops. The first type of noise is usually sparse and random, that could be easily taken care of by checking if any edges is next that noise point is also counted as an edge. If not, then the point is most defiantly noise and should be removed.
However, the second type of noise, where we have a semi continuous line about x=y poses more of a problem. The line is sometimes continuous for random lengths (the longest was it went half way across my entire array unbroken). It is even possible for it to intersect the actual edge.
Any ideas on how to do this?
| 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 own enable_if_c
template<bool value> struct enable_if_c { typedef void type; };
template<> struct enable_if_c< false > {};
//Class that has the overloaded member function
class TestClass
{
public:
void Func(float value) { printf( "%f\n", value ); }
void Func(int value) { printf( "%i\n", value ); }
};
//Struct to detect if TestClass has an overloaded member function for type T
template<typename T>
struct HasFunc
{
template<typename U, void (TestClass::*)( U )> struct SFINAE {};
template<typename U> static char Test(SFINAE<U, &TestClass::Func>*);
template<typename U> static int Test(...);
static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};
//Use enable_if_c to only allow the function call if TestClass has a valid overload for T
template<typename T> typename enable_if_c<HasFunc<T>::Has>::type CallFunc(TestClass &test, T value) { test.Func( value ); }
int main()
{
float value1 = 0.0f;
int value2 = 0;
TestClass testClass;
CallFunc( testClass, value1 ); //Should call TestClass::Func( float )
CallFunc( testClass, value2 ); //Should call TestClass::Func( int )
}
The error message is: no instance of function template "CallFunc" matches the argument list. It seems that HasFunc::Has is false for int and float when it should be true.
Is this a bug in the Comeau compiler? Am I doing something that's not standard? And if so, what do I need to do to fix it?
Update
I guess the question now becomes, if this is a bug, is there anything I can do to work around it? I tried using a static_cast on &TestClass::Func, but either that isn't possible or I didn't get the syntax right because I couldn't get it to compile.
If that's not a solution, is there any modifications I can make either to TestClass or HasFunc in order to work around the issue?
| 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_i;}
~Foo() {}
private:
int m_i;
};
class Bar
{
public:
Bar() :
m_foo( 5 ), //this is ok
m_myInt( m_foo.getInt() ) //runtime error, seg 11
{}
~Bar() {}
private:
Foo m_foo;
int m_myInt;
};
When trying to call member functions of members initialized higher up the initializer list, I get seg faults. I seem to recall this is a known problem (or perhaps somehow by design) but I've never seen it well described. The attached example is contrived with plain old data types, but substitute the Bar::m_myInt with another object lacking a default (empty) constructor and the issue is more real. Can anyone enlighten me?
| 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.
The concrete example that you have posted should compile and run without problems.
|
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_unique(vector<T> X) {
set<T> Y(X.begin(), X.end());
return X.size() == Y.size();
}
The second looping over the elements:
template <class T>
bool is_unique2(vector<T> X) {
typename vector<T>::iterator i,j;
for(i=X.begin();i!=X.end();++i) {
for(j=i+1;j!=X.end();++j) {
if(*i == *j) return 0;
}
}
return 1;
}
I've tested them the best I can, and from what I can gather from reading the documentation about STL, the answer is (as usual), it depends. I think that in the first case, if all the elements are unique it is very quick, but if there is a large degeneracy the operation seems to take O(N^2) time. For the nested iterator approach the opposite seems to be true, it is lighting fast if X[0]==X[1] but takes (understandably) O(N^2) time if all the elements are unique.
Is there a better way to do this, perhaps a STL algorithm built for this very purpose? If not, are there any suggestions eek out a bit more efficiency?
| 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 recommend sorting a vector of pointers to the objects.
template< class T >
bool dereference_less( T const *l, T const *r )
{ return *l < *r; }
template <class T>
bool is_unique(vector<T> const &x) {
vector< T const * > vp;
vp.reserve( x.size() );
for ( size_t i = 0; i < x.size(); ++ i ) vp.push_back( &x[i] );
sort( vp.begin(), vp.end(), ptr_fun( &dereference_less<T> ) ); // O(N log N)
return adjacent_find( vp.begin(), vp.end(),
not2( ptr_fun( &dereference_less<T> ) ) ) // "opposite functor"
== vp.end(); // if no adjacent pair (vp_n,vp_n+1) has *vp_n < *vp_n+1
}
or in STL style,
template <class I>
bool is_unique(I first, I last) {
typedef typename iterator_traits<I>::value_type T;
…
And if you can reorder the original vector, of course,
template <class T>
bool is_unique(vector<T> &x) {
sort( x.begin(), x.end() ); // O(N log N)
return adjacent_find( x.begin(), x.end() ) == x.end();
}
|
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_PRINT(result);
result = VssHandle->InitializeForBackup();
printf("unexpected%x\n",result);
system("pause");
return 0;
}
in the above program intializeforbackup fails with error code E_UNEXPECTED. The VSS service is running . In the event log it shows as "Volume Shadow Copy Service error: Unexpected error calling routine CoCreateInstance. hr = 0x800401f0.".. Any solutions for the InitializeForBackup to return S_OK?
| 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 Variable?
SDL_Surface* ball::ball_image = SDL_LoadBMP("ball.bmp");
| 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 requires a simple wrapper class.
struct smart_sdl_surface {
SDL_Surface *handle;
explicit smart_sdl_surface( char const *name )
: handle( SDL_LoadBMP( name ) ) {}
~smart_sdl_surface()
{ SDL_FreeSurface( handle ); }
};
class ball
{
private:
static smart_sdl_surface ball_image_wrapper;
static SDL_Surface *& ball_image; // reference to the ptr inside wrapper
};
smart_sdl_surface ball::ball_image_wrapper( "ball.bmp" );
SDL_Surface *&ball::ball_image = ball::ball_image_wrapper.handle;
When the program initializes, the constructor is called and the file is read. When the program exits, the destructor is called and the object is destroyed.
|
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 inside an instance named X2 inside an instance named X1. Got it?
There's really no "regular" character that cannot be used as a part of an instance name, so you resort to a non-printable one, or ... perhaps one outside of the standard 0..127 ASCII chars.
I thought I'd try (decimal) 166, because for me it shows up as the pipe: ¦.
So... I've got some C++ code which constructs the path name using ¦ as the hierarchical separator, so the path above looks like X1¦X2/X3¦X4.
Now the GUI is written in Tcl/Tk, and to properly translate this into human readable terms I need to do something like the following:
set path [getPathFromC++] ;# returns X1¦X2/X3¦X4
set humanreadable [join [split $path ¦] /]
Basically, replace the ¦ with / (I could also accomplish this with [string map]).
Now, the problem is, the ¦ in the string I get from C++ doesn't match the ¦ I can create in Tcl. i.e. This fails:
set path [getPathFromC++] ;# returns X1¦X2/X3¦X4
string match $path [format X1%cX2/X3%cX4 166 166]
Visually, the two strings look identical, but string match fails. I even tried using scan to see if I'd mixed up the bit values. But
set path [getPathFromC++] ;# returns X1¦X2/X3¦X4
set path2 [format X1%cX2/X3%cX4 166 166]
for {set i 0} {$i < [string length $path]} {incr i} {
set p [string range $path $i $i]
set p2 [string range $path2 $i $i]
scan %c $p c
scan %c $p2 c2
puts [list $p $c :::: $p2 $c2 equal? [string equal $c $c2]]
}
Produces output which looks like everything should match, except the [string equal] fails for the ¦ characters with a print line:
¦ 166 :::: ¦ 166 equal? 0
For what it's worth, the character in C++ is defined as:
const char SEPARATOR = 166;
Any ideas why a character outside the regular ASCII range would fail like this? When I changed the separator to (decimal) 28 (^\), things worked fine. I just don't want to get bit by a similar problem on a different platform. (I'm currently using Redhat Linux).
| 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 as a UTF-8 string. You need to convert your C++ string to UTF-8 before passing it to any TCL C functions. TCL provides some functions for this purpose.
You can read more about TCL and UTF-8.
|
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 baffled about the others. If I understand it correctly, I have to set some flags first?
Advice and/or a pointer to some literature would be appreciated.
Edit: the values returned in the double variable are 1.#INF or -1.#IND. I was wrong to call them strings.
| 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 to want to do something like this:
#include <float.h>
#pragma fenv_access (on)
void main()
{
unsigned int fp_control_word;
unsigned int new_fp_control_word;
_controlfp_s(&fp_control_word, 0, 0);
// Make the new fp env same as the old one,
// except for the changes we're going to make
new_fp_control_word = fp_control_word | _EM_INVALID | _EM_DENORMAL | _EM_ZERODIVIDE | _EM_OVERFLOW | _EM_UNDERFLOW | _EM_INEXACT;
//Update the control word with our changes
_controlfp_s(&fp_control_word, new_fp_control_word, _MCW_EM)
}
Some of the confusion here may be over the use of the word "exception". In C++, that's usually referring to the language built-in exception handling system. Floating point exceptions are a different beast altogether. The exceptions a standard FPU is required to support are all defined in IEEE-754. These happen inside the floating-point unit, which can do different things depending on how the float-point unit's control flags are set up. Usually one of two things happens:
1) The exception is ignored and the FPU sets a flag indicating an error occurred in its status register(s).
2) The exception isn't ignored by the FPU, so instead an interrupt gets generated, and whatever interrupt handler was set up for floating-point errors gets called. Usually this does something nice for you like causing you to break at that line of code in the debugger or generating a core file.
You can find more on IEE-754 here: http://www.openwatcom.org/ftp/devel/docs/ieee-754.pdf
Some additional floating-point references:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
http://floating-point-gui.de/
|
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 would be on the right.
Any idea how to code in Matlab or c++? I'd imaging it'd be a matrix flipped about the x axis and rotated 90 degrees but I'm at a total loss.
Phil
| 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, chips, and drink
struct item sandwich{"Sandwich", 3.00}; **** error is here *****
struct item chips{"Chips", 1.50}; **** error is here *****
struct item drink{"Large Drink", 2.00}; **** error is here *****
vector<item> cart; //vector to hold the items
double total = 0.0; //total
const double tax = 0.0825; //tax
//gets item choice from user
char getChoice(){
cout << "Select an item:" << endl;
cout << "S: Sandwich. $3.00" << endl;
cout << "C: Chips. $1.50" << endl;
cout << "D: Drink. $2.00" << endl;
cout << "X: Cancel. Start over" << endl;
cout << "T: Total" << endl;
char choice;
cin >> choice;
return choice;
}
//displays current items in cart and total
void displayCart(){
cout << "\nCart:" << endl;
for(unsigned int i=0; i<cart.size(); i++){
cout << cart.at(i).name << ". $" << cart.at(i).price << endl;
}
cout << "Total: $" << total << endl << endl;
}
//adds item to the cart
void addItem(struct item bought){
cart.push_back(bought);
total += bought.price;
displayCart();
}
//displays the receipt, items, prices, subtotal, taxes, and total
void displayReceipt(){
cout << "\nReceipt:" << endl;
cout << "Items: " << cart.size() << endl;
for(unsigned int i=0; i<cart.size(); i++){
cout << (i+1) << ". " << cart.at(i).name << ". $" << cart.at(i).price << endl;
}
cout << "----------------------------" << endl;
cout << "Subtotal: $" << total << endl;
double taxes = total*tax;
cout << "Tax: $" << taxes << endl;
cout << "Total: $" << (total + taxes) << endl;
}
int main(){
//sentinel to stop the loop
bool stop = false;
char choice;
while (stop == false ){
choice = getChoice();
//add sandwich
if( choice == 's' || choice == 'S' ){
addItem(sandwich);
}
//add chips
else if( choice == 'c' || choice == 'C' ){
addItem(chips);
}
//add drink
else if( choice == 'd' || choice == 'D' ){
addItem(drink);
}
//remove everything from cart
else if( choice == 'x' || choice == 'X' ){
cart.clear();
total = 0.0;
cout << "\n***** Transcation Canceled *****\n" << endl;
}
//calcualte total
else if( choice == 't' || choice == 'T' ){
displayReceipt();
stop = true;
}
//or wront item picked
else{
cout << choice << " is not a valid choice. Try again\n" << endl;
}
}//end while loop
return 0;
//end of program
}
| 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't been able to find much.
Any ideas??
| 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
Aaaand my personal favorite - Qt
Although, if you use this it's difficult to just use the file-system portion of it. You pretty much have to port your entire application over to Qt specific classes.
|
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. Can someone please explain it to me?
My second goal is to be able to perform an operation where the left operand is a double and the right operand is a logarithm object.
Here's a snippet of my log class:
// coefficient: double
// base: unsigned int
// result: double
class _log {
double coefficient, result;
unsigned int base;
public:
_log() {
base = 10;
coefficient = 0.0;
result = 0.0;
}
_log operator+ ( const double b ) const;
_log operator* ( const double b ) const;
_log operator- ( const double b ) const;
_log operator/ ( const double b ) const;
_log operator<< ( const _log &b );
double getValue() const;
bool changeBase( unsigned int base );
};
You guys are awesome, thank you for your time.
| 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 followed by an uppercase
letter (2.11) is reserved to the
implementation for any use.
Each name that begins with an underscore is reserved to the
implementation for use as a name in
the global namespace.165
165) Such names are also reserved in namespace ::std (17.4.3.1).
I'm guessing that you used _log instead of log due to the clash with log() in cmath. It is a Very Bad Idea to keep your own classes in the standard namespace for this very reason. Maybe the next version of the standard will provide a _log or Logarithm class?
Wrap your own class in namespace somename {} and reference it by using somename::Logarithm()
As others have mentioned already You need to declare your operator overloading as friend. Instead of what you have
log operator+ ( const double b ) const;
change it to
friend log operator+(const double d, const log& l);
and define the function in the namespace scope.
Here is the math for the change of base formula
Coefficient in math means the part that is being multiplied by the log. So if you had
A log_b(x) = y
A is the coefficient, B is the base, and Y is the result (or some other names)
|
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 add +1 to the depth? Something like that?
No idea about the algorithm for descendants. They are asking about the number of nodes a specific node has under itself.
These are normal trees btw.
| 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;
}
generates this compile time error:
main.cpp: In function int main(int,
char**)': main.cpp:46: error: request
for memberpush_back' in string1',
which is of non
-class typestd::vector > ()()'
I tried this with a vector of ints and strings as well and they had the same problem.
| 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>
constexpr std::size_t length(void)
{
return 1; // length of 1 element
}
template<typename T, typename... Args>
constexpr std::size_t length(void)
{
return 1 + length<Args...>(); // length of one element + rest
}
}
template<typename... Args>
constexpr std::size_t length(Args...)
{
return detail::length<Args...>(); // length of all elements
}
Note, everything is completely untested.
|
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.h>
#include <stdio.h>
#include <time.h>
using namespace std;
string header_str = ("NULL");
int main()
{
for(;;)
{
stringstream header(stringstream::in | stringstream::out);
header << "datasdasdasd_";
time_t rawtime;
time ( &rawtime );
header << ctime (&rawtime);
header_str = header.str();
fstream filestr;
filestr.open ("C:\\test.txt", fstream::in | fstream::out | fstream::app | ios_base::binary | ios_base::out);
for(;;)
{
filestr << (header_str);
}
filestr.close();
}
return 0;
}
anyone know how to fix this?
| 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 terminator.
#define DTTMFMT "%Y-%m-%d %H:%M:%S "
#define DTTMSZ 21
static char *getDtTm (char *buff) {
time_t t = time (0);
strftime (buff, DTTMSZ, DTTMFMT, localtime (&t));
return buff;
}
int main(void) {
char buff[DTTMSZ];
fstream filestr;
filestr.open ("test.txt", fstream::out|fstream::app);
// And this is how you call it:
filestr << getDtTm (buff) << "Your message goes here" << std::endl;
filestr.close();
return 0;
}
This creates the file test.txt with the contents:
2010-05-05 13:09:13 Your message goes here
|
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 operands. For one which is a member of a class, the first operand is the "implicit argument" which becomes this.
The implicit argument is different from the first argument to a free function in a few ways:
Its type is reference-to-class, whereas the free function can declare any type for its first argument.
It does not participate in implicit type conversion. (It will not be a temporary initialized by a conversion constructor.)
It does participate in virtual override resolution. (A virtual overload will be chosen by the dynamic type of the first operand, which is not possible with free functions without extra code.)
The situation is the same for unary, binary, or n-ary (in the case of operator()).
Members privilege of mutation: Operators which change the first operand (eg +=, =, prefix ++) should be implemented as member functions, and should exclusively implement the guts of all overloads. Postfix ++ is a second-class citizen; it is implemented as Obj ret = *this; ++ this; return ret;. Note that this sometimes extends to copy-constructors, which may contain *this = initializer.
Rule of freedom for commuters: Only commutative operators (eg /) should be free functions; all other operators (eg unary anything) should be members. Commutative operators inherently make a copy of the object; they are implemented as Obj ret = lhs; ret @= rhs; return ret; where @ is the commutative operator and lhs and rhs are left-hand side and right-hand side arguments, respectively.
Golden rule of C++ friendship: Avoid friendship. friend pollutes the semantics of a design. Overloading corollary: Overloading is simple if you follow the above rules, then friend is harmless. friending boilerplate overload definitions allows them to be placed inside the class { braces.
Note that some operators cannot be free functions: =, ->, [], and (), because the standard specifically says so in section 13.5. I think that's all… I thought unary & and * were too, but I was apparently wrong. They should always be overloaded as members, though, and only after careful thought!
|
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 new CBitmap
|
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(), PixelFormat32bppARGB);
Graphics TempGraphics(pTempBitmap);
TempGraphics.DrawImage(m_pGDIBitmap, Point(0,0));
|
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 templates are combined with concepts; see Section 3.3.
(Section 3.3 talks about concepts which is irrelevant now.)
|
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 correct?), GCC must be specifying the semantics itself.
I figure const_cast and static_cast cast between related types, hence they are safe, while reinterpret_cast can break strict aliasing rules.
Is this a correct understanding?
| 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 through a lvalue of another type is present in C89/90 (6.3) as well as in C++98 (3.10/15). That's what strict aliasing is all about, no more, no less. It is just that not all compilers wanted (or dared) to enforce it or rely on it. Both C and C++ languages are sometimes used as "high-level assembly" languages and strict aliasing rules often interfere with such uses. It was GCC that made that bold move and decided to start relying on strict aliasing rules in optimizations, often drawing complaints from those "assembly" types.
It is true that the most straightforward way to break strict aliasing rules in C++ is reinterpret_cast (and C-style cast, of course). However, static_cast can also be used for that purpose, since it allows one to break strict aliasing by using void * as an intermediate type in a "chained" cast
int *pi;
...
double *pd = static_cast<double *>(static_cast<void *>(pi));
const_cast cannot break strict aliasing in a compliant compiler.
As for C99... What C99 did introduce was the restrict qualifier. This is directly related to aliasing, but it is not what is known as strict aliasing per se.
|
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", 1},
{"QTESTLONGNAME", 2},
{"QTEST2", 3},
{"QIEC", 4}
};
| 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 time to create multiple handles in my process.
Please help me to solve this issue or give some tips...
| 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 call is attempted again
}
In this example the class is designed in such a way that the destructor could be called multiple times - no things like double-deletion can happen. The memory is still allocated at the point where delete is called - the first destructor call doesn't call the ::operator delete() to release memory.
For example, in Visual C++ 9 the above code looks working. Even C++ definition of UB doesn't directly prohibit things qualified as UB from working. So for the code above to break some implementation and/or platform specifics are required.
Why exactly would the above code break and under what conditions?
| 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 do. And neither does the standard. Its in those functions that things can potentially fall apart.
As a trivial example, lets say the compiler inserts code to track object lifetimes for debugging purposes. The constructor [which is also a magic function that does all sorts of things you didn't ask it to] stores some data somewhere that says "Here I am." Before the destructor is called, it changes that data to say "There I go". After the destructor is called, it gets rid of the information it used to find that data. So the next time you call the destructor, you end up with an access violation.
You could probably also come up with examples that involve virtual tables, but your sample code didn't include any virtual functions so that would be cheating.
|
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 by undefined behavior seem to be too large to be justified by these arguments. What are other arguments for undefined behavior? If there are none, why does undefined behavior still exist?
Edit To add some motivation for my question: Due to several bad experiences with less C++-crafty co-workers I have gotten used to making my code as safe as possible. Assert every argument, rigorous const-correctness and stuff like that. I try to leave as little room has possible to use my code the wrong way, because experience shows that, if there are loopholes, people will use them, and then they will call me about my code being bad. I consider making my code as safe as possible a good practice. This is why I do not understand why undefined behavior exists. Can someone please give me an example of undefined behavior that cannot be detected at runtime or compile time without considerable overhead?
| 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 course specifying the handling proper. However detecting it is against the speed first philosophy of the languages!
Today, do we still need fast programs ? Yes, for those of us working either with very limited resources (embedded systems) or with very harsh constraints (on response time or transactions per second), we do need to squeeze out as much as we can.
I know the motto throw more hardware at the problem. We have an application where I work:
expected time for an answer ? Less than 100ms, with DB calls in the midst (say thanks to memcached).
number of transactions per second ? 1200 in average, peaks at 1500/1700.
It runs on about 40 monsters: 8 dual core opteron (2800MHz) with 32GB of RAM. It gets difficult to be "faster" with more hardware at this point, so we need optimized code, and a language that allows it (we did restrain to throw assembly code in there).
I must say that I don't care much for UB anyway. If you get to the point that your program invokes UB then it needs fixing whatever the behavior that actually occurred. Of course it would be easier to fix them if it was reported straight away: that's what debug builds are for.
So perhaps that instead of focusing on UB we should learn to use the language:
don't use unchecked calls
(for experts) don't use unchecked calls
(for gurus) are you sure you really need an unchecked call here ?
And everything is suddenly better :)
|
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 compiling (Intel Compiler 11.0)
1>C:\projects\svn\bdk\Source\ZenithAssignment\src\Iteration\PtBranchAndBoundIterationOriginRunner.cpp(85): error: no operator "[]" matches these operands
1> operand types are: const std::map<int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>, std::less<int>, std::allocator<std::pair<const int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>>>> [ const int ]
1> vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt];
1> ^
I know it's got to be something silly but I can't see what I've done wrong.
UPDATE I'm calling this from a const member function which is why the member variable's type is const so I thought that something like the following should fix it:
int dest = 0, tt = 6;
const set<int>& egressCandidateStops = m_egressCandidatesByDestAndOtMode[tt].at(dest);
But no dice... still the same error.
|
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.
Step 3 is incompatible with constness.
Rather than have two
differently-functioning operator[]
overloads, the language forces you to
use map::find for const objects.
|
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 now I need server application developed for Linux. So I think code or application in C, C++, or Java will be required.
Can anyone suggest me some socket server application, code or link ?
Thanks,
Miraaj
| 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 concurrency in Java is also really easy, and often necessary when writing network programs. Just googling java socket should get your the documentation from sun's website for that.
Your C++ solution will just use the unix sockets api, so it would be no different than the C solution. For this reason, I see it as unnecessary to use C++.
Edit: So, I recently tried boost.asio. It's a decent solution if you like the async paradigm, try it with C++!
|
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 private. The effect is, that the only way to call this method is like this:
base_class *object = new derived_class();
object->do_something();
If you declare the object as of type derived_class, you can't call the method because it's private:
derived_class *object = new derived_class();
object->do_something();
// --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class'
I think this is quite nice, because if you create an abstract class that is used as an interface, you can make sure that nobody accidentally declares a field as the concrete type, but always uses the interface class.
Since in C# / .NET in general, you aren't allowed to narrow the access from public to private when overriding a method, is there a way to achieve a similar effect here?
| 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 IMyInterface. If the declaration uses the interface type, there is no casting needed in subsequent uses.
MSDN page on explicit interface implementation (thanks Luke, saves me a few seconds^^)
IMyInterface instance = new MyImplementation();
instance.MyMethod();
MyImplementation instance2 = new MyImplementation();
instance2.MyMethod(); // Won't compile with an explicit implementation
((IMyInterface)instance2).MyMethod();
|
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 an IDE, then Code::Blocks also comes as a complete system. This has recently (Jul-2010) been heavily improved, and comes with the GCC 4.4.1 compiler, if you want it. You might also want to look at CodeLite, which is also fairly easy to install.
|
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 VS2008 using stdext::hash_set.
| 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_equal(const UnorderedContainer& c1, const UnorderedContainer& c2)
{
typedef typename UnorderedContainer::value_type Element;
typedef typename UnorderedContainer::const_iterator Iterator;
typedef std::pair<Iterator, Iterator> IteratorPair;
if (c1.size() != c2.size())
return false;
for (Iterator it(c1.begin()); it != c1.end(); ++it)
{
IteratorPair er1(c1.equal_range(*it));
IteratorPair er2(c2.equal_range(*it));
if (std::distance(er1.first, er1.second) !=
std::distance(er2.first, er2.second))
return false;
// A totally naive implementation of is_permutation:
std::vector<Element> v1(er1.first, er1.second);
std::vector<Element> v2(er2.first, er2.second);
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
if (!std::equal(v1.begin(), v1.end(), v2.begin()))
return false;
}
return true;
}
It returns that hs1 and hs2 from your example are equal. (Somebody let me know if you spot a bug in that code; I didn't really test it extensively...)
I'll file a defect report on Microsoft Connect.
|
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 in real programming , I cant think of any real time scenarios where we really need to call functions/CTOR in our destructor. Usually , destructor is meant for cleaning up.
If my understanding is correct, why the compiler doesn't complain ? Is this because it is valid for some good reasons ? If so what are they ?
I tried on Sun Forte, g++ and VC++ compiler and none of them complain about it.\
Edit : I thank everyone for their answers, I think I didn't cut my point clearly, I knew the result , it will end up recursively and the program can crash, but the question actually is on Destructor allowing to create an object.
using namespace std;
class test{
public:
test(){
cout<<"CTOR"<<endl;
}
~test() {cout<<"DTOR"<<endl;
test();
}};
| 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 overflow and crashes your program.
Prohibiting the destructor from creating temporary objects would be ridiculous - it would severely limit you in what code you could right. Also it makes no sense - the destructor is destroying the current object, and those temporary object are completely irrelevant to it, so enforcing such constrains on them is meaningless.
|
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 expression tree. The branch nodes are operators randomly selected from an array, and the leaf nodes are values or the variable 'x', also randomly selected from an array.
char *values[10]={"1.0","2.0","3.0","4.0","5.0","6.0","7.0","8.0","9.0","x"};
char *ops[4]={"+","-","*","/"};
As this will be called billions of times during a run of the genetic algorithm of which it is a part, I'd like to optimize it for speed. I have a number of questions on this topic which I will ask in separate postings.
The first is: how can I get access to each 'cargo' as it is found. That is: instead of pushing 'cargo' onto a deque, and then processing the deque to get the value, I'd like to start processing it right away.
Edit: This question suggests that processing the deque afterwards is a better way.
I don't yet know about parallel processing in c++, but this would ideally be done concurrently on two different processors.
In python, I'd make the function a generator and access succeeding 'cargo's using .next().
See the above Edit.
But I'm using c++ to speed up the python implementation. I'm thinking that this kind of tree has been around for a long time, and somebody has probably optimized it already. Any Ideas? Thanks
| 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 loop forever, checking the size of the queue. If it's not empty, then lock the queue, pull off all available cargo and process it. Repeat loop. If no cargo available sleep for a short period of time and repeat.
If the locking is too expensive you can build up a queue of queues: First you put say 100 items into a cargo queue, and then put that queue into a locked queue (like the first example). Then start on a new "local" queue and continue.
|
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 for small webpages but if I go to large sites like tigerdirect.ca and browse through a couple of layers it is very slow and sometimes requests don't complete and I see broken images and javascript errors. This happens with all of our vendor sites and other content heavy sites.
Mentalis uses HTTP 1.0 which I know is not as efficient but should a proxy be that slow? What is an acceptable amount of performance loss from using a proxy? Would HTTP 1.1 make a noticeable difference?
Would a C++ proxy be much faster than one in C#? Is the Mentalis code just not efficient?
Would I be able to use a premade C++ proxy and import the DLL to C# and still get good performance or would this project call for all C++?
Sorry if these are obvious questions but I have not done network programming before.
EDIT In response to Joshua's question: I don't necessarily need to write the core proxy server myself as long as there is a good implementation out there but like I said I have been experimenting with Mentalis which isn't performing that well. The final application needs to install on a Windows PC/Server from a single installer with 0 manual configuration.
I can write all the necessary registry edits in the installer as I have done that before in C#.
UPDATE I took Aaronaught's advice and looked into improving Mentalis' code. I fix a problem so it works with HTTP 1.1 allowing it to work with Chrome and Firefox (Safari 4 on Windows crashes the proxy though for some reason).
When I tested in FireFox and Chrome I discovered the performance problems were not there which implied it was an IE problem not a problem with the proxy. After resetting the browsing history settings the problem went away.
Thanks everyone!
| 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 you'd have to learn the entire language from scratch, which is a huge negative (hard to come up with a good design when you barely know the tools).
Things you'll probably have to understand for this type of application:
I/O completion ports
Thread pools and multi-threading in general
Networking protocols (including HTTP, FTP, TCP, etc.) - especially for error handling
Certificates and signing/encryption (for SSL/HTTPS)
...
Honestly, you're talking about a non-trivial undertaking here. I don't mean to sound overly negative but what makes you think you can do a better job without an extensive knowledge of the underlying networking protocols and proxy design? Why not take a look at the Mentalis Proxy source code instead and see if you can improve it, rather than trying to write your own from scratch? Surely the former would be easier than the latter.
Anyway, a socket is a socket; .NET sockets are not much more than paper-thin wrappers over Windows sockets, so performance is not going to be noticeably different in C++.
|
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* > collection;
stores a collection of pointers to objects of type SomeClass, whereas the other two store collections of objects of type SomeClass.
As for why you "shouldn't use it," std::vector, which is part of the C++ language standard, and thus portable, is probably a better choice for most projects. If you have legacy code that uses CArray, then you may need to use it, and there's nothing wrong with that.
|
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 standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.
Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.
Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.
|
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 isn't good practice in C++). I have two scenarios: First, we have f created. Then you use &f in order to fill with zero. The second is a pointer *pf. I'm not sure how to set pf to all 0's like the previous example in C++.
Could you just do pf = new foo instead of malloc and then call memset(pf, 0, sizeof(foo))?
struct foo { ... } f;
memset( &f, 0, sizeof(f) );
//or
struct foo { ... } *pf;
pf = (struct foo*) malloc( sizeof(*pf) );
memset( pf, 0, sizeof(*pf) );
| 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 forget the corresponding delete. Even better would be to use shared_ptr :)
|
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 *value= (float *)byteArrayData.data();
Am I just implementing this wrong or is there a better way to do it using Qt?
Thanks
| 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), sizeof(f));
Should do it as well.
To go the other way around, you just have to perform the reverse operation:
float f2;
if (array.size() >= sizeof(f2)
{
f2 = *reinterpret_cast<const float*>(array.data());
} else
{
// The array is not big enough.
}
|
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 per-socket basis.
But in setsockopt, it is mentioned about SO_RCVBUF :
Specifies the total per-socket buffer
space reserved for receives. This is
unrelated to SO_MAX_MSG_SIZE and does
not necessarily correspond to the size
of the TCP receive window.
So is it possible? How?
Thanks.
| 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 _UUID_ in .vimrc is:
autocmd bufnewfile *.h exe "1,$s/_UUID_/" . r!uuidgen ."/g"
The problem is coming in under r!uuidgen. How do i insert the result of a shell-command-execution as text in the autocmd line? Or in a vi substitution command for that matter?
| 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++;
}
}
cout << "Found " << counter << " derived classes";
One line in the code is NOT correct. How should I write it properly? Many thanks in advance!
| 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 just fine).
Note that this also requires Base to have a vtable (virtual functions and/or destructor), because non-polymorphic types just don't have a dynamic type which typeid checks (that is, they would all be instances of Base as far as typeid is concerned).
If you don't have any virtual functions, then you'll need to emulate this yourself. For example, if you like string comparisons and don't mind the overhead, add a field to Base that each type will fill out in its constructor and compare those. Otherwise use a unique integral identifier for each subtype etc.
|
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>
<height>490</height>
</rect>
</property>
</widget>
The ui_mainform.h file:
#include <QtGui/QStatusBar>
#include <QtGui/QTabWidget>
#include <QtGui/QWidget>
#include <qscrollpane.h>
This isn't a big deal on Windows or Mac, but on Linux it's downright annoying. I could create a symlink to solve the issue, but I want to find the root cause.
Regards,
-Chris
| 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 (disclaimer: tested only on Windows Qt 4.6.1).
I prefer using all lowercase filenames for my classes - I'm always 100% sure I won't be screwed up by some non 100% cross-platform tool.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.