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,871,601 | 2,871,613 | Inheritance and static variables | Here is my code -
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
int a;
};
//int Base::a = 5;
class Derived : public Base
{
public:
int static a;
};
int main()
{
Derived d;
cout<<d.a;
getch();
return 0;
}
I get a linker error here. But when I do it the other way round -
class Base
{
public:
int static a;
};
int Base::a = 5;
class Derived : public Base
{
public:
int a;
};
I get no error. Can someone please explain what is happening here.
| All static members have to be explicitly defined/initialized outside the class.
In the second example you do this correctly (int Base::a=5), but in the first example you don't do this for Derived::a, adding the following line to the first example should solve it:
int Derived::a = 5;
|
2,871,905 | 3,203,888 | OpenAL - determine maximum sources | Is there an API that allows you to define the maximum number of OpenAL "sources" allowed by the underlying sound hardware?
Searching the internet, I found 2 recommendations :
keep generating OpenAL sources till you get an error. However, there is a note in FreeSL (OpenAL wrapper) stating that this is "very bad and may even crash the library"
assume you only have 16; why would anyone ever require more? (!)
The second recommendation is even adopted by FreeSL.
So, is there a common API to define the number of simultaneous "voices" supported?
Thank you for your time,
Bill
| update:
I can't find a way to determine what the maximum number of sources a device supports, but I think I've found how to determine the maximum a context supports(ALC_MONO_SOURCES). It would follow that a context supports the same number as its parent device.
//error checking omitted for brevity
ALCdevice* device = alcOpenDevice(NULL);
ALCcontext* context = alcCreateContext(device,NULL);
ALCint size;
alcGetIntegerv( device, ALC_ATTRIBUTES_SIZE, 1, &size);
std::vector<ALCint> attrs(size);
alcGetIntegerv( device, ALC_ALL_ATTRIBUTES, size, &attrs[0] );
for(size_t i=0; i<attrs.size(); ++i)
{
if( attrs[i] == ALC_MONO_SOURCES )
{
std::cout << "max mono sources: " << attrs[i+1] << std::endl;
}
}
This returns 255 on Ubuntu 10.4 using the stock OpenAL driver.
The long answer is well kinda...
Software based OpenAL drivers generally allow an infinite number of sources. Well, not really infinite, eventually you'll max out either the CPU or the RAM eventually.
Most hardware based OpenAL drivers only support as many sources as the hardware has channels. Modernly that is at least 16, probably 32 or more but can be as much as 256. There are probably sound cards that support more but 256 is the largest I've ever looked at.
On Windows DirectSound based drivers are arbitrarily limited to 31 (why not 32?) sources. DirectSound has been deprecated so I don't know if this still applies to Vista and Windows 7.
The iPhone supports 32 sources.
I have seen one hardware based driver that was software backed. Meaning it would give each source a hardware channel until they ran out. Then it would mix some of the sounds in software before shipping it off the the hardware. This gives the best of both worlds, near infinite sources, while still using as much hardware acceleration as possible.
In practice if you're using a hardware based driver, just keep creating them until alGenSources fails. I have heard this doesn't work on the iPhone. There a some software based OpenAL drivers that will crash before alGenSources fails.
There really ought to be an API to check the max number of sources and number of sources that are hardware accelerated. Maybe there is in the extensions.
|
2,871,906 | 2,871,943 | Containers of auto pointers | I know containers of auto pointers should not be used and can cause problems. What is the actual reason for that? Is there any other kind of "smart" pointer which is safe to use in a container?
| Container elements should be truly copyable; auto_ptr's are not. If you make a copy, the original is modified (it loses ownership). A boost::shared_ptr can be copied, as the two pointers will share ownership afterwards. Thus, it can be used in a STL container.
|
2,872,073 | 2,872,095 | Is throwing an exception a healthy way to exit? | I have a setup that looks like this.
class Checker
{ // member data
Results m_results; // see below
public:
bool Check();
private:
bool Check1();
bool Check2();
// .. so on
};
Checker is a class that performs lengthy check computations for engineering analysis. Each type of check has a resultant double that the checker stores. (see below)
bool Checker::Check()
{ // initilisations etc.
Check1();
Check2();
// ... so on
}
A typical Check function would look like this:
bool Checker::Check1()
{ double result;
// lots of code
m_results.SetCheck1Result(result);
}
And the results class looks something like this:
class Results
{ double m_check1Result;
double m_check2Result;
// ...
public:
void SetCheck1Result(double d);
double GetOverallResult()
{ return max(m_check1Result, m_check2Result, ...); }
};
Note: all code is oversimplified.
The Checker and Result classes were initially written to perform all checks and return an overall double result. There is now a new requirement where I only need to know if any of the results exceeds 1. If it does, subsequent checks need not be carried out(it's an optimisation). To achieve this, I could either:
Modify every CheckN function to keep check for result and return. The parent Check function would keep checking m_results. OR
In the Results::SetCheckNResults(), throw an exception if the value exceeds 1 and catch it at the end of Checker::Check().
The first is tedious, error prone and sub-optimal because every CheckN function further branches out into sub-checks etc.
The second is non-intrusive and quick. One disadvantage is I can think of is that the Checker code may not necessarily be exception-safe(although there is no other exception being thrown anywhere else). Is there anything else that's obvious that I'm overlooking? What about the cost of throwing exceptions and stack unwinding?
Is there a better 3rd option?
| I don't think this is a good idea. Exceptions should be limited to, well, exceptional situations. Yours is a question of normal control flow.
It seems you could very well move all the redundant code dealing with the result out of the checks and into the calling function. The resulting code would be cleaner and probably much easier to understand than non-exceptional exceptions.
Change your CheckX() functions to return the double they produce and leave dealing with the result to the caller. The caller can more easily do this in a way that doesn't involve redundancy.
If you want to be really fancy, put those functions into an array of function pointers and iterate over that. Then the code for dealing with the results would all be in a loop. Something like:
bool Checker::Check()
{
for( std::size_t id=0; idx<sizeof(check_tbl)/sizeof(check_tbl[0]); ++idx ) {
double result = check_tbl[idx]();
if( result > 1 )
return false; // or whichever way your logic is (an enum might be better)
}
return true;
}
Edit: I had overlooked that you need to call any of N SetCheckResultX() functions, too, which would be impossible to incorporate into my sample code. So either you can shoehorn this into an array, too, (change them to SetCheckResult(std::size_t idx, double result)) or you would have to have two function pointers in each table entry:
struct check_tbl_entry {
check_fnc_t checker;
set_result_fnc_t setter;
};
check_tbl_entry check_tbl[] = { { &Checker::Check1, &Checker::SetCheck1Result }
, { &Checker::Check2, &Checker::SetCheck2Result }
// ...
};
bool Checker::Check()
{
for( std::size_t id=0; idx<sizeof(check_tbl)/sizeof(check_tbl[0]); ++idx ) {
double result = check_tbl[idx].checker();
check_tbl[idx].setter(result);
if( result > 1 )
return false; // or whichever way your logic is (an enum might be better)
}
return true;
}
(And, no, I'm not going to attempt to write down the correct syntax for a member function pointer's type. I've always had to look this up and still never ot this right the first time... But I know it's doable.)
|
2,872,155 | 2,874,560 | Howcome some C++ functions with unspecified linkage build with C linkage? | This is something that makes me fairly perplexed.
I have a C++ file that implements a set of functions, and a header file that defines prototypes for them.
When building with Visual Studio or MingW-gcc, I get linking errors on two of the functions, and adding an 'extern "C"' qualifier resolved the error. How is this possible?
Header file, "some_header.h":
// Definition of struct DEMO_GLOBAL_DATA omitted
DWORD WINAPI ThreadFunction(LPVOID lpData);
void WriteLogString(void *pUserData, const char *pString, unsigned long nStringLen);
void CheckValid(DEMO_GLOBAL_DATA *pData);
int HandleStart(DEMO_GLOBAL_DATA * pDAta, TCHAR * pLogFileName);
void HandleEnd(DEMO_GLOBAL_DATA *pData);
C++ file, "some_implementation.cpp"
#include "some_header.h"
DWORD WINAPI ThreadFunction(LPVOID lpData) { /* omitted */ }
void WriteLogString(void *pUserData, const char *pString, unsigned long nStringLen) { /* omitted */ }
void CheckValid(DEMO_GLOBAL_DATA *pData) { /* omitted */ }
int HandleStart(DEMO_GLOBAL_DATA * pDAta, TCHAR * pLogFileName) { /* omitted */ }
void HandleEnd(DEMO_GLOBAL_DATA *pData) { /* omitted */ }
The implementations compile without warnings, but when linking with the UI code that calls these, I get a normal
error LNK2001: unresolved external symbol "int __cdecl HandleStart(struct _DEMO_GLOBAL_DATA *, wchar_t *)
error LNK2001: unresolved external symbol "void __cdecl CheckValid(struct _DEMO_MAIN_GLOBAL_DATA *
What really confuses me, now, is that only these two functions (HandleStart and CheckValid) seems to be built with C linkage. Explicitly adding "extern 'C'" declarations for only these two resolved the linking error, and the application builds and runs.
Adding "extern 'C'" on some other function, such as HandleEnd, introduces a new linking error, so that one is obviously compiled correctly.
The implementation file is never modified in any of this, only the prototypes.
| The error indicates that nothing is wrong with your implementation file or header (as used by the implementation file) - the link error strongly suggests that the functions actually generated were generated with c++ linkage - Its the UI file thats incorrectly looking for the C-Linkage versions of the functions. Patching the definitions in the header is patching your implementation to conform to the probably incorrect demands of the UI, rather than the other way around.
Your UI file is either a .m or .c file, OR , if your UI file is a .cpp file you have dome something like:
// ui.cpp
extern "C" {
#include "some_header.h"
}
Of course, if your UI file is a .c file - you either need to change it to cpp, OR explicitly define the functions with C-linkage so they can be called from C.
|
2,872,841 | 2,872,881 | Do I have to start from beginning? | If I have:
std::size_t bagCapacity_ = 10;
std::size_t bagSize = 0;
A** bag = new A*[bagCapacity_];
while (capacity--)
{
bag[capacity] = new A(bagSize++); //**here I'm loading this array from the end is it ok?**
}
And also can I delete those object from starting at the end of the array?
while (capacity--)
{
delete bag[capacity];
}
Question in a code.
| here I'm loading this array from the end is it ok?
Yes, that is fine. You can fill the elements anyway you like.
delete[] bag[capacity];
This code is wrong. bag[capacity] is of type A* which is allocated using new and not new[] hence you should not do delete[] you should do only delete bag[capacity]; to delete individual A objects. At the end you should be delete[] bag to delete the memory allocated for the bag.
|
2,872,958 | 2,872,970 | RegQueryValueEx not working with a Release version but working fine with Debug | I'm trying to read some ODBC details from a registry and for that I use RegQueryValueEx. The problem is when I compile the release version it simply cannot read any registry values.
The code is:
CString odbcFuns::getOpenedKeyRegValue(HKEY hKey, CString valName)
{
CString retStr;
char *strTmp = (char*)malloc(MAX_DSN_STR_LENGTH * sizeof(char));
memset(strTmp, 0, MAX_DSN_STR_LENGTH);
DWORD cbData;
long rret = RegQueryValueEx(hKey, valName, NULL, NULL, (LPBYTE)strTmp, &cbData);
if (rret != ERROR_SUCCESS)
{
free(strTmp);
return CString("?");
}
strTmp[cbData] = '\0';
retStr.Format(_T("%s"), strTmp);
free(strTmp);
return retStr;
}
I've found a workaround for this - I disabled Optimization (/Od), but it seems strange that I needed to do that. Is there some other way? I use Visual Studio 2005. Maybe it's a bug in VS?
Almost forgot - the error code is 2 (as the key wouldn't be found).
| You need to initialize cbData - set it to be MAX_DSN_STR_LENGTH - 1 before calling RegQueryValueEx().
The problem is likely configuration-dependent because the variable is initialized by the compiler in one configuration and left uninitialized in another.
Also you'll be much better of using std::vector for the buffer - less code, better exception safety, less error-prone.
|
2,873,128 | 2,876,218 | C++/Qt Apps on Ovi Store? | Can one develop C++/Qt based application for Symbian and N series phone and upload the same to Ovi store ?.
I hear conflicting stories. I understand the existence of Smart Installer etc.
But my question is as of today can I code and ship apps to Ovi store ?.
If not any clue how long before it becomes a reality ?.
Ankur
Update: http://ht.ly/1PvcI says mid 2010 is when it ships. I also heard from a Qt Developer that is ships along with 4.7 release. Worse case they say is September 2010
| Today it is not possible to publish applications developed with Qt in Ovi Store. The problem is, that today very few phones have Qt installed. For this, Nokia created the smart installer, that would be asked to install the correct version of Qt from the internet, but still not stable. Something can be done is to link the application statically, but the executable is something more than 10 mb and passed the capacity constraints Ovi Store. In the near future (after the second half of this year) is expected to SmartInstaller is stable and officially supported by Ovi, which would allow to publish the applications based in Qt Framework!.
|
2,873,255 | 2,873,282 | TCP Message Structure with XML | I'm sending messages over TCP/IP and on the other side I parse TCP message.For example this is one of the sent messages.
$DKMSG(requestType=REQUEST_LOGIN&requestId=123&username=metdos&password=123)$EDKMSG
Clarification:
$DKMSG( //Start
)$EDKMSG //End
requestType //Parameter
REQUEST_LOGIN //Parameter Value
Now I also want to add an Xml file to my message. I'm considering this option:
$DKMSG(requestType=REQUEST_LOGIN&xmlData=
<Item id="56D@MIT" type="SIGNAL">
<Label>
<Text>56D</Text>
<X1>10</X1>
<Y1>40</Y1>
<RotateAngle>90</RotateAngle>
</Label>
<X1>0</X1>
<Y1>20</Y1>
<Width>35</Width>
<Height>10</Height>
<Source>sgs3lr</Source>
</Item>
)$EDKMSG
There are problems with this way:
1-)It doesn't seem right to me.
2-)I have to handle delimeter "=" with much more care or I need to change it in parameters.
What are your suggestions, thanks.
| This looks like a homegrown format. You should use something out-of-the-box instead, like JSON, XML, protocol buffers, or even the young upstart: BERT, which even specifies an RPC protocol that uses the format. These formats all have parsers written for them in several languages, and they are all supported on C++.
|
2,873,381 | 2,874,901 | How to call a C++ function that takes a reference from C# code | HI,
I have a C++ function like the following:
int ShowJob(const JobData& data);
How does this translate to a DLLImport statement which I can use to call the function from C#?
| This could only work if JobData is a structure. You're dead in the water if it is a class, you cannot create a C++ class instance in C#. You don't have access to the constructor and destructor.
The "const" keyword is an attribute checked by the C++ compiler, it has no relevance to C# code. A C++ reference is a pointer under the hood, you'll get one by declaring the argument with "ref". You're likely to have a problem getting the "ShowJob" export name right, it is normally decorated by the C++ compiler. You'd suppress that decoration by prefixing the function with extern "C" in the C++ code. If you cannot change the C++ code then you can find the exported name by running Dumpbin.exe /exports on the DLL.
Putting this all together, the declarations ought to resemble something like this:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct JobData {
// members...
}
[DllImport("something.dll", EntryPoint = "?ShowJob@@YAHABUJobData@@@Z", CallingConvention = CallingConvention.Cdecl)]
private static extern int ShowJob(ref JobData data);
Lot's of guess work going on here, you'll need to verify this with your actual C++ code. If the JobData argument is in fact a class then you'll need to write a ref class wrapper in the C++/CLI language.
|
2,873,579 | 2,873,607 | c++ generic pointer to (member?) function | I can't seem to declare a generic pointer to function.
Having these 2 functions to be called:
void myfunc1(std::string str)
{
std::cout << str << std::endl;
}
struct X
{
void f(std::string str){ std::cout<< str << std::endl;}
};
and these two function callers:
typedef void (*userhandler_t) (std::string);
struct example
{
userhandler_t userhandler_;
example(userhandler_t userhandler): userhandler_(userhandler){}
void call(std::string str)
{
userhandler_(str);
}
};
template<typename func_t>
void justfunc(func_t func)
{
func("hello, works!");
}
when I try to use them with boost::bind to call the member function they give me compile errors.
this works:
example e1(&myfunc1);
e1.call("hello, world!");
justfunc(&myfunc1);
this doesn't:
X x;
example e2(boost::bind(&X::f, &x, _1));
e2.call("hello, world2!");
justfunc(boost::bind(&X::f, &x, _1));
How is this supposed to be done?
| boost::bind creates objects that behave like functions, not actual function pointers. Use the Boost.Function library to hold the result of calling boost::bind:
struct example
{
boost::function<void(std::string)> userhandler_;
...
};
|
2,873,692 | 2,874,755 | For programming content, what simple-to-use-and-setup PHP based blog are the preferred ones? | I've since long wanted a place I can toss my programming related nuggets at. Every day I feel I solve something that I'll surely hit again in a not so distant future, but by then I most certainly will have forgotten about the previous solution I came up with.
So I need to blog it down, quick and dirty, for my own documentation and memory's sake.
Must be easy to set up and use.
Must handle code syntax and highlighting gracefully for a number of languages, but mainly C# and C++.
Must be PHP-based, because that's what my host supplies.
I know and have used WordPress (not for code, though), but is it really what I want or need?
| I've always used WordPress for this and have had great results. If you go that route, there are two syntax highlighter plugins in particular I'd recommend looking into.
Syntax Highlighter Evolved
http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/
This one uses square brackets ([ ]) to denote your code blocks and provides line numbering, but you have to use the "copy to clipboard" or "view source" buttons it generates when copying more than one line of code, otherwise the line numbers get copied too. It's uses the SyntaxHighlighter Javascript package for the code highlighting.
Sample syntax
[css].foo {bar:'baz';}[/css]
[sourcecode language="plain"]your code here[/sourcecode]
WP-Syntax
http://wordpress.org/extend/plugins/wp-syntax/
WP-Syntax - my highlighter of choice for WordPress - uses <pre> tags to signify blocks of code. Like Syntax Highlighter Evolved, it also offers line numbering options, but with the distinct difference that the line numbers don't get selected when copying/pasting from code examples. WP-Syntax uses GeSHi for its highlighting.
Sample syntax
<pre lang="php">
$debug = print_r($foo, true);
$debug .= print_r($bar, true);
echo '<pre>' . $debug . '</pre>';
</pre>
|
2,873,714 | 2,873,735 | Is it possible to use a DLL created using C# in an unmanaged VC++ application? | I have a DLL that I wrote in C# and I want to use it both with C# applications and applications written in unmanaged VC++. Is this possible?
| To supplement other answers here, here's the MS support article which describes your scenario.
http://support.microsoft.com/kb/828736
|
2,873,721 | 2,875,350 | Oracle Extended Stored Procedure with C++ | I am currently adding Oracle 10.2.0. as a viable database to a product. The product originally allows connection to SQL Server and I have found some extended stored procedures.
Is it possible to produce similar extended stored procedures for Oracle with C++?
If so, how do I accomplish this? Example code would be much appreciated.
| You will need to use Oracle External Procedures.
Here is a discussion on getting the environment set up properly - it's tricky.
Asktom.com has an interesting discussion.
Be aware there are several security issues to be concerned with.
|
2,873,802 | 2,873,883 | Specify template parameters at runtime | Consider the following template class
class MyClassInterface {
public:
virtual double foo(double) = 0;
}
class MyClass<int P1, int P2, int P3>
: public MyClassInterface {
public:
double foo(double a) {
// complex computation dependent on P1, P2, P3
}
// more methods and fields (dependent on P1, P2, P3)
}
The template parameters P1, P2, P3 are in a restricted range like from 0 to some fixed value n fixed at compile time.
Now I would like to build a "factory" method like
MyClassInterface* Factor(int p1, int p2, int p3) {
return new MyClass<p1,p2,p3>(); // <- how to do this?
}
The question would be how to achieve the construction of the template class when template parameters are only known at runtime. And would the same be possible with template parameters having a very large domain (like a double)? Please consider also, if the possible solution is extendable to using more template parameters.
| Here's what you can do:
MyClassInterface* Factor(int p1, int p2, int p3) {
if (p1 == 0 && p2 == 0 && p3 == 0)
return new MyClass<0,0,0>();
if (p1 == 0 && p2 == 0 && p3 == 1)
return new MyClass<0,0,1>();
etc;
}
Note that this does not even remotely scale to floating point values. It scales only to a known list of discrete values.
I've also used this bit of code before to do some template automatic generation:
#include <boost/preprocessor.hpp>
#define RANGE ((0)(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)(12))
#define MACRO(r, p) \
if (BOOST_PP_SEQ_ELEM(0, p) == var1 && BOOST_PP_SEQ_ELEM(1, p) == var2 && BOOST_PP_SEQ_ELEM(2, p) == var3 && BOOST_PP_SEQ_ELEM(3, p) == var4) \
actual_foo = foo<BOOST_PP_TUPLE_REM_CTOR(4, BOOST_PP_SEQ_TO_TUPLE(p))>;
BOOST_PP_SEQ_FOR_EACH_PRODUCT(MACRO, RANGE RANGE RANGE RANGE)
#undef MACRO
#undef RANGE
The compiler produces output that looks like this:
if (0 == var1 && 0 == var2 && 0 == var3 && 0 == var4) actual_foo = foo<0, 0, 0, 0>;
if (0 == var1 && 0 == var2 && 0 == var3 && 1 == var4) actual_foo = foo<0, 0, 0, 1>;
if (0 == var1 && 0 == var2 && 0 == var3 && 2 == var4) actual_foo = foo<0, 0, 0, 2>;
if (0 == var1 && 0 == var2 && 0 == var3 && 3 == var4) actual_foo = foo<0, 0, 0, 3>;
if (0 == var1 && 0 == var2 && 0 == var3 && 4 == var4) actual_foo = foo<0, 0, 0, 4>;
if (0 == var1 && 0 == var2 && 0 == var3 && 5 == var4) actual_foo = foo<0, 0, 0, 5>;
if (0 == var1 && 0 == var2 && 0 == var3 && 6 == var4) actual_foo = foo<0, 0, 0, 6>;
if (0 == var1 && 0 == var2 && 0 == var3 && 7 == var4) actual_foo = foo<0, 0, 0, 7>;
if (0 == var1 && 0 == var2 && 0 == var3 && 8 == var4) actual_foo = foo<0, 0, 0, 8>;
etc...
Also, please note that with this method, with 4 variables, each ranging over 13 values, You would cause the compiler to instantiate 28561 copies of this function. If your n was 50, and you still had 4 options, you would have 6250000 functions instantiated. This can make for a SLOW compile.
|
2,874,164 | 2,874,196 | Hold a network connection although IP address change | Is it possible to hold an open TCP connection with a client, while the IP address of the client is externally changed?
For example, the connection is establishes against address X, but somewhen while the connection is open, the client-side user asks for IP renew and gets another IP address. Can the connection remains alive in this case?
Thanks in advance.
| No, it cannot.
Even if the local side could be massaged to understand that the connection is suddenly between different addresses, the remote side will not understand and will refuse to work with it.
You'd need to re-add the old IP address to continue using the connection.
To do so:
Linux: ip addr add 172.16.10.20/22 dev bond0
Windows: do some pointy-clicky or**fill in command here**
|
2,874,198 | 2,874,352 | Using boost::random to select from an std::list where elements are being removed | See this related question on more generic use of the Boost Random library.
My questions involves selecting a random element from an std::list, doing some operation, which could potentally include removing the element from the list, and then choosing another random element, until some condition is satisfied.
The boost code and for loop look roughly like this:
// create and insert elements into list
std::list<MyClass> myList;
//[...]
// select uniformly from list indices
boost::uniform_int<> indices( 0, myList.size()-1 );
boost::variate_generator< boost::mt19937, boost::uniform_int<> >
selectIndex(boost::mt19937(), indices);
for( int i = 0; i <= maxOperations; ++i ) {
int index = selectIndex();
MyClass & mc = myList.begin() + index;
// do operations with mc, potentially removing it from myList
//[...]
}
My problem is as soon as the operations that are performed on an element result in the removal of an element, the variate_generator has the potential to select an invalid index in the list. I don't think it makes sense to completely recreate the variate_generator each time, especially if I seed it with time(0).
| I assume that MyClass & mc = myList.begin() + index; is just pseudo code, as begin returns an iterator and I don't think list iterators (non-random-access) support operator+.
As far as I can tell, with variate generator your three basic options in this case are:
Recreate the generator when you remove an item.
Do filtering on the generated index and if it's >= the current size of the list, retry until you get a valid index. Note that if you remove a lot of indexes this could get pretty inefficient as well.
Leave the node in the list but mark it invalid so if you try to operate on that index it safely no-ops. This is just a different version of the second option.
Alternately you could devise a different index generation algorithm that's able to adapt to the container changing size.
|
2,874,403 | 2,882,131 | Strip OLE header information (MS Access / SQL Server) | I have a C++ application that needs to support binary database content (images, etc). When using MS Access or MS SQL Server this data is wrapped inside an OLE object. How do I strip this OLE header information? Note that I can't just look for the beginning of a specific tag as the content can be png, jpg and a whole heap of other formats. Should I use something like COleDataObject?
| Using MS Access 2007 (I need to test other MS databases) the format seems to be:
84 bytes
file name + \0
full path + \0
5 bytes + [2] bytes (the third byte of those five bytes)
temp path + \0
4 bytes
actual data (if not using a link to the file)
So far I simply parse and strip the part before the actual data, but I'm still wondering if there's no way to use something like COleDataSource to help parse this information more robustly.
Also note that this format only applies for generic content (start tag 0x15 0x1c 0x32). When using bitmaps (start tag 0x15 0x1c 0x2f) there's a fixed offset of 78 bytes and when using PowerPoint (start tag 0x15 0x1c 0x34) there's a fixed offset of 95 bytes.
|
2,874,441 | 2,874,533 | Deleting elements from std::set while iterating | I need to go through a set and remove elements that meet a predefined criteria.
This is the test code I wrote:
#include <set>
#include <algorithm>
void printElement(int value) {
std::cout << value << " ";
}
int main() {
int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::set<int> numbers(initNum, initNum + 10);
// print '0 1 2 3 4 5 6 7 8 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
std::set<int>::iterator it = numbers.begin();
// iterate through the set and erase all even numbers
for (; it != numbers.end(); ++it) {
int n = *it;
if (n % 2 == 0) {
// wouldn't invalidate the iterator?
numbers.erase(it);
}
}
// print '1 3 5 7 9'
std::for_each(numbers.begin(), numbers.end(), printElement);
return 0;
}
At first, I thought that erasing an element from the set while iterating through it would invalidate the iterator, and the increment at the for loop would have undefined behavior. Even though, I executed this test code and all went well, and I can't explain why.
My question:
Is this the defined behavior for std sets or is this implementation specific? I am using gcc 4.3.3 on ubuntu 10.04 (32-bit version), by the way.
Thanks!
Proposed solution:
Is this a correct way to iterate and erase elements from the set?
while(it != numbers.end()) {
int n = *it;
if (n % 2 == 0) {
// post-increment operator returns a copy, then increment
numbers.erase(it++);
} else {
// pre-increment operator increments, then return
++it;
}
}
Edit: PREFERED SOLUTION
I came around a solution that seems more elegant to me, even though it does exactly the same.
while(it != numbers.end()) {
// copy the current iterator then increment it
std::set<int>::iterator current = it++;
int n = *current;
if (n % 2 == 0) {
// don't invalidate iterator it, because it is already
// pointing to the next element
numbers.erase(current);
}
}
If there are several test conditions inside the while, each one of them must increment the iterator. I like this code better because the iterator is incremented only in one place, making the code less error-prone and more readable.
| This is implementation dependent:
Standard 23.1.2.8:
The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.
Maybe you could try this -- this is standard conforming:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
numbers.erase(it++);
}
else {
++it;
}
}
Note that it++ is postfix, hence it passes the old position to erase, but first jumps to a newer one due to the operator.
2015.10.27 update:
C++11 has resolved the defect. iterator erase (const_iterator position); return an iterator to the element that follows the last element removed (or set::end, if the last element was removed). So C++11 style is:
for (auto it = numbers.begin(); it != numbers.end(); ) {
if (*it % 2 == 0) {
it = numbers.erase(it);
}
else {
++it;
}
}
|
2,874,527 | 2,878,811 | libiconv - iconv_open() default behavior? | According to the documentation of iconv_open() over: http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_open.3.html
"//TRANSLIT" means that when a character cannot be represented in the target character set, it can be approximated through one or several characters.
and:
"//IGNORE" means that characters that cannot be represented in the target character set will be silently discarded.
But what is the default behavior, when neither are specified?
Thanks, Doori Bar
| The default behaviour is to stop conversion and return -1, with errno set to EILSEQ if an character that cannot be converted to the target character set is encountered.
(ie. This is different to both //TRANSLIT and //IGNORE).
|
2,874,540 | 2,875,651 | How to query a CGI based webserver from an app written in MFC (MSVC 2008) and process the result? | I am exploring the option of querying a web-page, which has a CGI script running on its end, with a search string (say in the form of http://sw.mycompany.com/~tools/cgi-bin/script.cgi?param1=value1¶m2=value2¶m3=value3 ), and displaying the result on my app (after due processing of course). My app is written in MFC C++ , and I must confess that I have never attempted anything related to network programming before.
Is what I'm trying to do very infeasible ? If not, could anyone point me at the resources I need to look at in order to go about this ?
Thanks !
| CInternetSession internet_session;
CHttpConnection* connection = NULL;
CHttpFile* file = NULL;
TRY {
connection = internet_session.GetHttpConnection("www.somehost.com", (INTERNET_PORT)80);
// URI needs to be a relative path here
file = connection->OpenRequest(CHttpConnection::HTTP_VERB_GET, "/some/file/on/server", NULL, 1, NULL, "HTTP/1.1");
BOOL send_result = file->SendRequest();
if (send_result == FALSE) {
// When can this happen? Only when connection fails between this and the previous call.
// Need to use ugly MFC exception stuff because OpenRequest et al. use it.
::AfxThrowInternetException(internet_session.GetContext());
}
}
CATCH (CInternetException, e) {
if (file) {
file->Close();
}
delete connection;
file = NULL;
connection = NULL;
}
END_CATCH
if (!file) {
delete file;
delete connection;
return false;
}
DWORD status_code;
file->QueryInfoStatusCode(status_code);
if (status_code != 200) {
CString result;
if (status_code == 403) {
result.Format("Authentication error (HTTP 403)");
} else if (status_code == 404) {
result.Format("Object not found (HTTP 404)");
} else if (status_code == 500) {
result.Format("Application error: malformed request (HTTP 500)");
} else {
result.Format("Got unsupported HTTP status code %d", status_code);
}
file->Close();
delete file;
delete connection;
return false;
}
|
2,874,576 | 2,874,584 | Simple map<> instantiation, I can't compile, please help | Why I can't compile this code?
#include <map>
using namespace std;
class MyTest {
template<typename T> void test() const;
};
template<typename T> void MyTest::test() const {
map<string, T*> m;
map<string, T*>::const_iterator i = m.begin();
}
My compiler says:
In member function ‘void MyTest::test() const’:
test.cpp:8: error: expected `;' before ‘i’
What is it about? Many thanks in advance!
| You have a dependent name, you need to append typename to the const_iterator because its type depends on the type of T.
template<typename T> void MyTest::test() const {
map<string, T*> m;
typename map<string, T*>::const_iterator i = m.begin();
}
C++ faq on depenent names
|
2,874,589 | 2,874,686 | Unoverloadable C++ operators | What operators can not be overloaded in C++?
| From Wikipedia:
Operator Name Syntax
Bind pointer to member by reference a.*b
Member a.b
Scope resolution a::b
Size of sizeof(a)
Ternary a ? b : c
Type identification typeid(a)
|
2,874,824 | 2,874,867 | Using C++ classes in .NET | I have a set of classes that I've written in C++ for a code base that will run in Linux commandline. They primarily use the STL and no fancy features of the language. They've been tested, and work.
I need to write a GUI app for the .NET framework that does things using logic I've written in those classes, but run on Windows. A critical requirement for the Windows app is that it behave exactly like the Linux app would. Hence, I'd like to share the code between the two code bases.
So, I'd like to import them (or so) into a new code base, and keep changes in sync between the two. Ideally, I'd like to write my .NET stuff in VB.NET, as I'm more familiar with that, but I'm willing to change to C# or C++ for .NET development.
My question is, how can I use those C++ classes (with minimal changes) in a .NET project? Is this even possible? Can I create a library or so in .NET?
NB: my .NET experience is limited, so I apologize if this is a newbie question.
| Yes, you can - you can use C++ code (as long as it doesn't depend on Linux-specific functionality) in a .NET application. C++/CLI is a superset of C++, offering access to the .NET managed classes and other features. Take your existing code, build it as a DLL (managed if you can, unmanaged if not), then create the GUI parts that call into it.
|
2,875,333 | 2,875,540 | Can any function be a deleted-function? | The working draft explicitly calls out that defaulted-functions must be special member functions (eg copy-constructor, default-constructor, etc, (§8.4.2.1-1)). Which makes perfect sense.
However, I don't see any such restriction on deleted-functions(§8.4.3). Is that right?
Or in other words are these three examples valid c++0?
struct Foo
{
// 1
int bar( int ) = delete;
};
// 2
int baz( int ) = delete;
template< typename T >
int boo( T t );
// 3
template<>
int boo<int>(int t) = delete;
| The C++0x spec (§[dcl.fct.def.delete]) doesn't deny such constructs, and g++ 4.5 recognize all 3 of them.
x.cpp: In function 'int main()':
x.cpp:4:8: error: deleted function 'int Foo::bar(int)'
x.cpp:21:11: error: used here
x.cpp:9:5: error: deleted function 'int baz(int)'
x.cpp:22:2: error: used here
x.cpp:9:5: error: deleted function 'int baz(int)'
x.cpp:22:8: error: used here
x.cpp:17:5: error: deleted function 'int boo(T) [with T = int]'
x.cpp:23:7: error: used here
|
2,875,536 | 2,875,626 | huge C file debugging problem | I have a source file in my project, which has more than 65,536 code lines (112,444 to be exact). I'm using an "sqlite amalgamation", which comes in a single huge source file.
I'm using MSVC 2005. The problems arrives during debugging. Everything compiles and links ok. But then when I'm trying to step into a function with the debugger - it shows an incorrect code line.
What's interesting is that the difference between the correct line number and the one the debugger shows is exactly 65536. This makes me suspect (almost be sure in) some unsigned short overflow.
I also suspect that it's not a bug in the MSVC itself. Perhaps it's the limitation of the debug information format. That is, the debug information format used by MSVC stores the line numbers as 2-byte shorts.
Is there anything can be done about this (apart from cutting the huge file into several smaller ones) ?
| According to a MS moderator, this is a known issue with the debugger only (the compiler seems to handle it fine as you pointed out). There is apparently no workaround, other than using shorter source files. See official response to very similar question here
|
2,875,580 | 2,875,627 | Variable arguments and function overloading | I am trying to improve SQLite error handling in an existing C++ program. I have a custom type SQLiteException, and I want to write a macro to print the line number, file name, and error messages from SQL.
I have the following functions defined:
LogMessage(LPCTSTR message); // Does the real work. Appends a timestamp to the message and logs the message to disk
LogMessage(LPCSTR message); // Simply converts message from ASCII to UNICODE and calls the original LogMessage(LPCTSTR message) function.
LogMessage(LPCTSTR message, ...); // A new variable argument version of the function. It uses vsprintf to format into a temporary TCHAR string, and passes that string into the first LogMessage(LPCTSTR message) function.
This is where I am having trouble. The compiler is complaining about ambigious call to overloaded function. The third function is implemented like this:
void LogMessage(LPCTSTR message, ...)
{
TCHAR logBuffer[513];
va_list args;
va_start(args, message);
_vsntprintf(logBuffer, 512, message, args);
va_end(args);
LogMessage((LPCTSTR)logBuffer);
}
}
The macro I have added is written like this:
#define LOG_SQLITE_EXCEPTION(e) LogMessage(_T("%s %s %d"), CString(__FUNCTION__), CString(__FILE__), __LINE__); LogMessage(GetSQLiteErrorMessage(e));
How can I make the compiler call the first version of the LogMessage function in the implementation of the third version? The compiler seems to be ignoring the '...' parameter and can't tell the difference between the first and third implementation of LogMessage.
| Well, these are variable arguments - meaning that zero arguments is also acceptable. In that case the compiler will not be able to pick between your first and third function as their first argument is identical.
|
2,875,740 | 2,875,769 | Pointing class property to another class with vectors | I've got a simple class, and another class that has a property that points to the first class:
#include <iostream>
#include <vector>
using namespace std;
class first{
public:
int var1;
};
class second{
public:
first* classvar;
};
Then, i've got a void that's supposed to point "classvar" to the intended iteration of the class "first".
void fill(vector<second>& sec, vector<first>& fir){
sec[0].classvar = &fir[0];
}
Finally the main(). Create and fill a vector of class "first", create "second" vector, and run the fill function.
int main(){
vector<first> a(1);
a[0].var1 = 1000;
vector<second> b(1);
fill(b, a);
cout << b[0].classvar.var1 << '\n';
system("PAUSE");
return 0;
}
This gives me the following error:
1>c:\...\main.cpp(29) : error C2228: left of '.var1' must have class/struct/union
1> type is 'first *'
And I can't figure out why it reads the "classvar" as the whole vector instead of just the single instance. Should I do this
cout << b[0].classvar[0].var1 << '\n';
it reads perfectly.
Can anyone figure out the problem?
Thanks in advance
| The problem is that b[0].classvar is a pointer. To access members of a class through a pointer, you must use the -> operator, not ..
The reason b[0].classvar[0].var1 works is because the index operator [] for pointers makes this equivalent to (*(b[0].classvar + 0)).var1. In other words, it adds 0 to the pointer and then dereferences it, so you can then access it with the dot operator.
|
2,875,801 | 2,875,822 | Is long long in C++ known to be very nasty in terms of precision? | The Given Problem:
Given a theater with n rows, m seats, and a list of seats that are reserved. Given these values, determine how many ways two friends can sit together in the same row.
So, if the theater was a size of 2x3 and the very first seat in the first row was reserved, there would be 3 different seatings that these two guys can take.
The Problem That I'm Dealing With
The function itself is supposed to return the number of seatings that there are based on these constraints. The return value is a long long.
I've gone through my code many many times...and I'm pretty sure that it's right. All I'm doing is incrementing this one value. However, ALL of the values that my function return differ from the actual solution by 1 or 2.
Any ideas? And if you think that it's just something wrong with my code, please tell me. I don't mind being called an idiot just as long as I learn something.
| Unless you're overflowing or underflowing, it definitely sounds like something is wrong with your code. For integral types, there are no precision ambiguities in c or c++
|
2,875,872 | 3,483,744 | gluLookAt alternative doesn't work | I'm trying to calculate a lookat matrix myself, instead of using gluLookAt().
My problem is that my matrix doesn't work. using the same parameters on gluLookAt does work however.
my way of creating a lookat matrix:
Vector3 Eye, At, Up; //these should be parameters =)
Vector3 zaxis = At - Eye; zaxis.Normalize();
Vector3 xaxis = Vector3::Cross(Up, zaxis); xaxis.Normalize();
Vector3 yaxis = Vector3::Cross(zaxis, xaxis); yaxis.Normalize();
float r[16] =
{
xaxis.x, yaxis.x, zaxis.x, 0,
xaxis.y, yaxis.y, zaxis.y, 0,
xaxis.z, yaxis.z, zaxis.z, 0,
0, 0, 0, 1,
};
Matrix Rotation;
memcpy(Rotation.values, r, sizeof(r));
float t[16] =
{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-Eye.x, -Eye.y, -Eye.z, 1,
};
Matrix Translation;
memcpy(Translation.values, t, sizeof(t));
View = Rotation * Translation; // i tried reversing this as well (translation*rotation)
now, when i try to use this matrix be calling glMultMatrixf, nothing shows up in my engine, while using the same eye, lookat and up values on gluLookAt works perfect as i said before.
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMultMatrixf(View);
the problem must be in somewhere in the code i posted here, i know the problem is not in my Vector3/Matrix classes, because they work fine when creating a projection matrix.
| I assume you have a right handed coordinate system (it is default in OpenGL).
Try the following code. I think you forgot to normalize up and you have to put "-zaxis" in the matrix.
Vector3 Eye, At, Up; //these should be parameters =)
Vector3 zaxis = At - Eye; zaxis.Normalize();
Up.Normalize();
Vector3 xaxis = Vector3::Cross(Up, zaxis); xaxis.Normalize();
Vector3 yaxis = Vector3::Cross(zaxis, xaxis); yaxis.Normalize();
float r[16] =
{
xaxis.x, yaxis.x, -zaxis.x, 0,
xaxis.y, yaxis.y, -zaxis.y, 0,
xaxis.z, yaxis.z, -zaxis.z, 0,
0, 0, 0, 1,
};
|
2,875,908 | 2,875,919 | Nested If (x) checks - Better way to write this? | There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.
For example, I have
if (a)
{
if (a->b())
{
if (a->b()->c())
{
a->b()->c()->DoSomething();
}
}
}
I really don't like the look of this. Is there a way to turn this into something more readable? Ideally,
if (a && a->b() && a->b()->c() )
{
...
}
would be great, but obviously would not work.
EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!
| Why would the latter not work?
In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.
In fact, you could write:
a && a->b() && a->b()->c() && a->b()->c()->DoSomething();
|
2,875,985 | 2,876,025 | C++ - No match for 'operator=' when compiling using GCC | I recently tried building my own shared and weak pointers. Code that compiles using Visual Studio doesn't compile in GCC (4.5.0) with the following error:
main.cpp: In function 'int main()':
main.cpp:18:27: error: no match for 'operator=' in 'wp1 = weak_ptr<int>(((const shared_ptr<int>&)((const shared_ptr<int>*)(& sp1))))'
weak_ptr.h:59:9: note: candidate is: void weak_ptr<T>::operator=(weak_ptr<T>&) [with T = int, weak_ptr<T> = weak_ptr<int>]
Here are the most important parts of my code:
1) Weak pointer implementation (note the declaration of operator=)
#include "smart_ptr_wrapper.hpp"
#include "shared_ptr.h"
template <typename T>
class weak_ptr {
private:
// Weak wrapper implementation
typedef smart_ptr_wrapper<T> weak_ptr_wrapper;
weak_ptr_wrapper* wrapper;
private:
// Shared wrapper additional routines
void increase_reference_count() {
++(wrapper->weak_count);
}
void decrease_reference_count() {
--(wrapper->weak_count);
// Dispose the wrapper if there are no more
// references to this object
// @note This should actually lock the wrapper to
// preserve thread safety
if (wrapper->strong_count == 0 && wrapper->weak_count == 0) {
delete wrapper;
}
}
public:
// Default constructor to grant syntax flexibility
weak_ptr() : wrapper(NULL) { }
weak_ptr(const shared_ptr<T>& pointer) : wrapper(pointer.wrapper) {
increase_reference_count();
}
weak_ptr(const weak_ptr& p) : wrapper(p.wrapper) {
increase_reference_count();
}
weak_ptr& operator= (weak_ptr& p) {
// Set new reference counts
// @note If this is 'just-a-pointer', which was created
// using default constructor then our wrapper would be 'NULL'
if (wrapper != NULL) {
decrease_reference_count();
}
p.increase_reference_count();
// Set new wrapper
wrapper = p.wrapper;
return *this;
}
~weak_ptr() {
decrease_reference_count();
}
T* get() const { return (wrapper->strong_count == 0) ? NULL: wrapper->raw_pointer; }
T* operator-> () const { return get(); }
T& operator* () const { return *get(); }
// User comparison operation
operator void* () const {
return (get() == NULL);
}
};
2) main.cpp
int main() {
shared_ptr<int> sp1(new int(4));
weak_ptr<int> wp1(sp1);
// Next line can't be compiled by gcc... Why?
wp1 = weak_ptr<int>(sp1);
return 0;
}
Q:
Why does this happen? I'm probably plain stupid, but I can't see what's wrong with this code and can't undestand GCC behaviour. I would also appreciate if someone could explain why does this code compile and why does it work under MSVS (I mean, why would one compiler do it fine and why would the second fail). Thank you.
Update: Full code and compiler error can be seen here - http://codepad.org/MirlNayf
| Your assignment operator requires a reference, not a const reference:
weak_ptr& operator= (weak_ptr& p)
However, the expression weak_ptr<int>(sp1) results in a temporary, which can only be converted to a const reference, since it is an rvalue. Think about it this way: you cannot modify the result of an expression, yet your assignment operator requires that it can.
The solution is to declare your assignment operator like this instead:
weak_ptr& operator= (const weak_ptr& p)
Why VC++ accepts this is beyond me... maybe you should enable some standards compliance flags.
|
2,876,274 | 2,876,353 | C++ OpenGL Window Kit | Besides Qt, GTK, wxWidgets... What are the recommendations for a cross platform, open source GUI framework library that works with OpenGL?
| Its not quite a GUI framework. But GLFW is good for an OpenGL window with some extra features like keyboard and joystick handling.
I found the other framework I was looking for. It is SFML. I only used it briefly but I do remember liking it very much. It does contain a lot of nice extras going a step further than GLFW. If I recall correctly the documentation was stellar.
For a full featured cross-platform GUI framework I think you would be hard pressed to beat QT, GTK, or wx.
|
2,876,357 | 2,876,374 | Determine the line of code that causes a segmentation fault? | How does one determine where the mistake is in the code that causes a segmentation fault?
Can my compiler (gcc) show the location of the fault in the program?
| GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:
gcc program.c -g
Then use gdb:
$ gdb ./a.out
(gdb) run
<segfault happens here>
(gdb) backtrace
<offending code is shown here>
Here is a nice tutorial to get you started with GDB.
Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides.
|
2,876,413 | 2,876,523 | C++ - gcc-specific warnings | Got the following warning output when using GCC 4.5.0 & MinGW.
Warning: .drectve `-aligncomm:___CTOR_LIST__,2 ' unrecognized
Warning: .drectve `-aligncomm:___DTOR_LIST__,2' unrecognized
What does it mean? I guess it's version-specific, because GCC 4.3.4 under cygwin didn't give that warning on the same project.
If anyone had the following output (just curious that's that about), please advise me what to do.
| Hmmm, Google does wonders:
GCC failure
Broken on Cygwin
The advice, try reloading and rebuilding GCC or load a prior version.
|
2,876,465 | 2,876,553 | Edit strings vars in compiled exe? C++ win32 | I want to have a few strings in my c++ app and I want to be able to edit them later in the deployed applications (the compiled exe), Is there a way to make the exe edit itself or it resources so I can update the strings value?
The app checks for updates on start, so I'm thinking about using that to algo send the command when I need to edit the strings (for example the string that contains the url used to check for updates).
I don't want to use anything external to the exe, I could simply use the registry but I prefer to keep everything inside the exe.
I am using visual studio 2010 c++ (or any other version of ms visual c++).
| Another idea is to move the strings into a "configuration" file, such as in XML or INI format.
Modifying the EXE without compilation is hacking and highly discouraged. You could use a hex editor, find the string and modify it. The new text must be have a length less than or equal to the original EXE.
Note, some virus checkers perform CRCs or checksums on the executables. Altering the executables is a red flag to these virus checkers.
|
2,876,535 | 2,876,678 | Simple and efficient distribution of C++/Boost source code (amalgamation) | My job mostly consists of engineering analysis, but I find myself distributing code more and more frequently among my colleagues. A big pain is that not every user is proficient in the intricacies of compiling source code, and I cannot distribute executables.
I've been working with C++ using Boost, and the problem is that I cannot request every sysadmin of every network to install the libraries. Instead, I want to distribute a single source file (or as few as possible) so that the user can g++ source.c -o program.
So, the question is: can you pack the Boost libraries with your code, and end up with a single file? I am talking about the Boost libraries which are "headers only" or "templates only".
As an inspiration, please look at the distribution of SQlite or the Lemon Parser Generator; the author amalgamates the stuff into a single source file which is trivial to compile.
Thank you.
Edit:
A related question in SO is for Windows environment. I work in Linux.
| There is a utility that comes with boost called bcp, that can scan your source and extract any boost header files that are used from the boost source. I've setup a script that does this extraction into our source tree, so that we can package the source that we need along with our code. It will also copy the boost source files for a couple of boost libraries that we use that are no header only, which are then compiled directly into our applications.
This is done once, and then anybody who uses the code doesn't even need to know that it depends on boost. Here is what we use. It will also build bjam and bcp, if they haven't been build already.
#!/bin/sh
BOOST_SRC=.../boost_1_43_0
DEST_DIR=../src/boost
TOOLSET=
if ( test `uname` = "Darwin") then
TOOLSET="--toolset=darwin"
fi
# make bcp if necessary
if ( ! test -x $BOOST_SRC/dist/bin/bcp ) then
if ( test -x $BOOST_SRC/tools/jam/*/bin.*/bjam ) then
BJAM=$BOOST_SRC/tools/jam/*/bin.*/bjam
else
echo "### Building bjam"
pushd $BOOST_SRC/tools/jam
./build_dist.sh
popd
if ( test -x $BOOST_SRC/tools/jam/*/bin.*/bjam ) then
BJAM=$BOOST_SRC/tools/jam/*/bin.*/bjam
fi
fi
echo "BJAM: $BJAM"
pushd $BOOST_SRC/tools/bcp
echo "### Building bcp"
echo "$BJAM $TOOLSET"
$BJAM $TOOLSET
if [ $? == "0" ]; then
exit 1;
fi
popd
fi
if ( ! test -x $BOOST_SRC/dist/bin/bcp) then
echo "### Couldn't find bpc"
exit 1;
fi
mkdir -p $DEST_DIR
echo "### Copying boost source"
MAKEFILEAM=$DEST_DIR/libs/Makefile.am
rm $MAKEFILEAM
# Signals
# copy source libraries
mkdir -p $DEST_DIR/libs/signals/src
cp $BOOST_SRC/libs/signals/src/* $DEST_DIR/libs/signals/src/.
echo -n "boost_sources += " >> $MAKEFILEAM
for f in `ls $DEST_DIR/libs/signals/src | fgrep .cpp`; do
echo -n "boost/libs/signals/src/$f " >> $MAKEFILEAM
done
echo >> $MAKEFILEAM
echo "### Extracting boost includes"
$BOOST_SRC/dist/bin/bcp --scan --boost=$BOOST_SRC ../src/*/*.[Ch] ../src/boost/libs/*/src/*.cpp ../src/smart_assert/smart_assert/priv/fwd/*.hpp $DEST_DIR
if [ $? != "0" ]; then
echo "### bcp failed"
rm -rf $DEST_DIR
exit 1;
fi
|
2,876,559 | 2,877,033 | Why is there garbage in my TCHAR, even after ZeroMemory()? | I have inherited the following line of code:
TCHAR temp[300];
GetModuleFileName(NULL, temp, 300);
However, this fails as the first 3 bytes are filled with garbage values (always the same ones though, -128, -13, 23, in that order). I said, well fine and changed it to:
TCHAR temp[300];
ZeroMemory(temp, 300);
GetModuleFileName(NULL, temp, 300);
but the garbage values persisted! Note that after the ZeroMemory() call, all other bytes were zeroed out properly and after GetModuleFileName(), the directory was stored in the buffer properly. It's as if temp was being replaced by temp+3. Could this have something to do with word boundaries?
Can someone explain what is going on and how to fix it?
| ZeroMemory works in terms of bytes, whereas you have an array of 300 TCHARs. This makes me assume you're working with widechar (not multi-byte) compilation option.
You should use:
ZeroMemory(temp, 300 * sizeof(TCHAR));
Or in your specific case:
ZeroMemory(temp, sizeof(temp));
However be careful with the latter. It's applicable if temp is an automatic array whose declaration is visible within the function. If it's a pointer whose allocation size is "invisible" for the compiler - sizeof will give just the size of the pointer.
|
2,876,641 | 2,880,062 | So can unique_ptr be used safely in stl collections? | I am confused with unique_ptr and rvalue move philosophy.
Let's say we have two collections:
std::vector<std::auto_ptr<int>> autoCollection;
std::vector<std::unique_ptr<int>> uniqueCollection;
Now I would expect the following to fail, as there is no telling what the algorithm is doing internally and maybe making internal pivot copies and the like, thus ripping away ownership from the auto_ptr:
std::sort(autoCollection.begin(), autoCollection.end());
I get this. And the compiler rightly disallows this happening.
But then I do this:
std::sort(uniqueCollection.begin(), uniqueCollection.end());
And this compiles. And I do not understand why. I did not think unique_ptrs could be copied. Does this mean a pivot value cannot be taken, so the sort is less efficient? Or is this pivot actually a move, which in fact is as dangerous as the collection of auto_ptrs, and should be disallowed by the compiler?
I think I am missing some crucial piece of information, so I eagerly await someone to supply me with the aha! moment.
| I think it's more a question of philosophy than technic :)
The underlying question is what is the difference between Move and Copy. I won't jump into technical / standardista language, let's do it simply:
Copy: create another identical object (or at least, one which SHOULD compare equal)
Move: take an object and put it in another location
As you said, it is possible to implement Move in term of Copy: create a copy into the new location and discard the original. However there are two issues there. One is of performance, the second is about objects used for RAII: which of the two should have ownership ?
A proper Move constructor solves the 2 issues:
It is clear which object has ownership: the new one, since the original will be discarded
It is thus unnecessary to copy the resources pointed to, which allows for greater efficiency
The auto_ptr and unique_ptr are a very good illustration of this.
With an auto_ptr you have a screwed Copy semantic: the original and the copy don't compare equal. You could use it for its Move semantic but there is a risk that you'll lose the object pointed to somewhere.
On the other hand, the unique_ptr is exactly that: it guarantees a unique owner of the resource, thus avoiding copying and the inevitable deletion issue that would follow. And the no-copy is guaranteed at compile-time too. Therefore, it's suitable in containers as long as you don't try to have copy initialization.
typedef std::unique_ptr<int> unique_t;
typedef std::vector< unique_t > vector_t;
vector_t vec1; // fine
vector_t vec2(5, unique_t(new Foo)); // Error (Copy)
vector_t vec3(vec1.begin(), vec1.end()); // Error (Copy)
vector_t vec3(make_move_iterator(vec1.begin()), make_move_iterator(vec1.end()));
// Courtesy of sehe
std::sort(vec1.begin(), vec1.end()); // fine, because using Move Assignment Operator
std::copy(vec1.begin(), vec1.end(), std::back_inserter(vec2)); // Error (copy)
So you can use unique_ptr in a container (unlike auto_ptr), but a number of operations will be impossible because they involve copying which the type does not support.
Unfortunately Visual Studio may be quite lax in the enforcement of the standard and also has a number of extensions that you would need to disable to ensure portability of the code... don't use it to check the standard :)
|
2,876,720 | 2,879,322 | C++ library to load Excel (.xls) files | I'm looking for a free C++ library that can load .xls files in both Windows and Linux. If I had to make a choice, Linux would be the bare minimum.
I've tried LibXL, but got this amazing error:
"can't read more cells in trial version"
So now I'm on the hunt for a free version :), unfortunately xlsLib doesn't provide the ability to load existing .xls files.
Thanks
| We have had success with: ExcelFormat
|
2,877,084 | 2,877,116 | Why does this code crash? | The following code causes a stack overflow but I don't see why...
int _tmain(int argc, _TCHAR* argv[])
{
cout << "start";
char bmp[1024][768][3];
for (int p = 0; p < 9000; ++p)
{
for(int i = 0; i < 1024; ++i)
{
for(int j = 0; j < 768; ++j)
{
bmp[i][j][0] = 20;
}
}
}
cout << "Stop";
return 0;
}
Thanks
| I would say it is likely because 1024 * 768 * 3 is 2,359,296 which is probably too big for the local stack.
You should instead allocate that on the heap.
|
2,877,175 | 2,877,601 | method chaining including class constructor | I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g:
Foo foo;
foo.bar().baz();
But as soon as the constructor call becomes part of the method chain, the compiler complains about expecting ";" in place of "." immediately after the constructor call:
Foo foo().bar().baz();
I'm wondering now if this is actually possible in C++. Here is my test class:
class Foo
{
public:
Foo()
{
}
Foo& bar()
{
return *this;
}
Foo& baz()
{
return *this;
}
};
I also found an example for "fluent interfaces" in C++ (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B) which seems to be exactly what I'm searching for. However, I get the same compiler error for that code.
| You have forgotten the actual name for the Foo object. Try:
Foo foo = Foo().bar().baz();
|
2,877,220 | 2,877,489 | Is typeid of type name always evaluated at compile time in c++? | I wanted to check that typeid is evaluated at compile time when used with a type name (ie typeid(int), typeid(std::string)...).
To do so, I repeated in a loop the comparison of two typeid calls, and compiled it with optimizations enabled, in order to see if the compiler simplified the loop (by looking at the execution time which is 1us when it simplifies instead of 160ms when it does not).
And I get strange results, because sometimes the compiler simplifies the code, and sometimes it does not. I use g++ (I tried different 4.x versions), and here is the program:
#include <iostream>
#include <typeinfo>
#include <time.h>
class DisplayData {};
class RobotDisplay: public DisplayData {};
class SensorDisplay: public DisplayData {};
class RobotQt {};
class SensorQt {};
timespec tp1, tp2;
const int n = 1000000000;
int main()
{
int avg = 0;
clock_gettime(CLOCK_REALTIME, &tp1);
for(int i = 0; i < n; ++i)
{
// if (typeid(RobotQt) == typeid(RobotDisplay)) // (1) compile time
// if (typeid(SensorQt) == typeid(SensorDisplay)) // (2) compile time
if (typeid(RobotQt) == typeid(RobotDisplay) ||
typeid(SensorQt) == typeid(SensorDisplay)) // (3) not compile time ???!!!
avg++;
else
avg--;
}
clock_gettime(CLOCK_REALTIME, &tp2);
std::cout << "time (" << avg << "): " <<
(tp2.tv_sec-tp1.tv_sec)*1000000000+(tp2.tv_nsec-tp1.tv_nsec) <<
" ns" << std::endl;
}
The conditions in which this problem appear are not clear, but:
- if there is no inheritance involved, no problem (always compile time)
- if I do only one comparison, no problem
- the problem only appears only with a disjunction of comparisons if all the terms are false
So is there something I didn't get with how typeid works (is it always supposed to be evaluated at compilation time when used with type names?) or may this be a gcc bug in evaluation or optimization?
About the context, I tracked down the problem to this very simplified example, but my goal is to use typeid with template types (as partial function template specialization is not possible).
Thanks for your help!
| I don't really know the answer to your question but if you use is_same<> metafunction instead of typeid you might get more desirable results. Even if you don't have access to this metafunction, it is very easy to write one:
template < typename T1, typename T2 >
struct is_same
{
enum { value = false }; // is_same represents a bool.
typedef is_same<T1,T2> type; // to qualify as a metafunction.
};
template < typename T >
struct is_same
{
enum { value = true };
typedef is_same<T,T> type;
};
|
2,877,234 | 2,877,285 | How to have transactions on objects | How I can imitate transactions on objects. For example, I want to delete the item from one collection and then add the same item to other collection as an atomic action. It is possible to do a lot of checks when something failed and to roll back everything but this is annoying.
Is there any technique (no difference what language (Java/C++/C#)) to achive this.
| For small, simple objects, you can use a copy-modify-swap idiom. Copy the original object. Make the changes. If all the changes succeeded, swap the copy with the original. (In C++, swap is typically efficient and no-fail.) The destructor will then clean up the original, instead of the copy.
In your case, you'd copy both collections. Remove the object from the first, add it to the second, and then swap the original collections with the copies.
However, this may not be practical if you have large or hard-to-copy objects. In those cases, you generally have to do more work manually.
|
2,877,295 | 2,877,357 | Get OS in c++ win32 for all versions of win? | How to get the OS version for all windows, at least the name for win95,98,me,xp,vista,7?
Im using visual c++ 2010 and I want to include this feature in a pure win32 app.
| Use GetVersionEx
http://msdn.microsoft.com/en-us/library/ms724451%28v=VS.85%29.aspx
|
2,877,319 | 2,877,498 | Why doesn't luazip extract files when called from c++ application? | I have a c++ application that interfaces with lua files. I have a lua file that extracts zip files, which works when I run it using SciTe or the Lua command line. But when I try to run it from a c++ application it doesn't seem to work.
require "zip"
function ExtractZipFiles(zipFilename, destinationPath)
zipFile, err = zip.open(zipFilename)
-- iterate through each file insize the zip file
for file in zipFile:files() do
currentFile, err = zipFile:open(file.filename)
currentFileContents = currentFile:read("*a") -- read entire contents of current file
currentFile:close()
hBinaryOutput = io.open(destinationPath .. file.filename, "wb")
-- write current file inside zip to a file outside zip
if(hBinaryOutput)then
hBinaryOutput:write(currentFileContents)
hBinaryOutput:close()
end
end
zipFile:close()
end
-- Unit Test
ExtractZipFiles("SZProcessTests.zip", "Infections\\")
If I have Lua installed on the computer and double-click on the lua file it runs and the files are extracted as expected. But, it doesn't work if I try to run the lua file from C++ like this:
void CSZTestClientMessagesDlg::OnBtnExecute()
{
L = lua_open();
luaL_openlibs(L);
luaL_dofile(L, "ExtractZipFiles.lua");
lua_close(L);
return;
}
| First of all check for errors:
if (luaL_dofile(L, "ExtractZipFiles.lua"))
{
std::cerr << "Lua error : " << lua_tostring(L, -1) << std::endl;
}
Apart from that, my guess is that Lua can't locate the zip module -- check your package paths settings, read about require in the Lua manual.
In general, you need to check where the zip module is (zip.lua?) and make sure it's accessible during runtime (you can manually load it for example if all else fails).
|
2,877,687 | 2,877,712 | Visual Studio C++: Seeing the ASM code? | I'd like to see all the asm produced by Visual Studio C++ to learn a bit about ASM, compilers, etc. I know with GCC, you can do it with the -S argument, but not in VS. How do I go about doing this?
| The easiest way to do this is to start your program in the integrated debugger, then turn on the assembly language view. This shows the assembly language interleaved with your original source code.
Back when I used VS, this was Alt+F7 or something but it's probably changed. The advantage of doing this (over using -S equivalent) is you can focus on exactly which line(s) of code you're interested in.
|
2,877,961 | 2,879,166 | How do you measure the effect of branch misprediction? | I'm currently profiling an implementation of binary search. Using some special instructions to measure this I noticed that the code has about a 20% misprediction rate. I'm curious if there is any way to check how many cycles I'm potentially losing due to this. It's a MIPS based architecture.
| Look it up in the docs for your CPU. If you can't find this information specifically, the length of the CPU's pipeline is a fairly good estimate.
Given that it's MIPS and it's a 300MHz system, I'm going to guess that it's a fairly short pipeline. Probably 4-5 stages, so a cost of 3-4 cycles per mispredict is probably a reasonable guess.
|
2,878,073 | 2,878,338 | Where are the function address literals in c++? | UPDATE: After some additional reading, what I really wanted was guaranteed early binding (which should translated to an immediate call for non-virtual functions and non-PIC code), which can be done by passing a (member) function as a template parameter. The problem I had was that gcc < 4.5 and icc 11.1 can generate some funky instructions for member function pointer template parameter calls. AFAICT, gcc >= 4,5 and vs2008 handle these template parameter calls fine.
First of all, maybe literals is not the right term for this concept, but its the closest I could think of (not literals in the sense of functions as first class citizens).
The idea is that when you make a conventional function call, it compiles to something like this:
callq <immediate address>
But if you make a function call using a function pointer, it compiles to something like this:
mov <memory location>,%rax
callq *%rax
Which is all well and good. However, what if I'm writing a template library that requires a callback of some sort with a specified argument list and the user of the library is expected to know what function they want to call at compile time? Then I would like to write my template to accept a function literal as a template parameter. So, similar to
template <int int_literal>
struct my_template {...};`
I'd like to write
template <func_literal_t func_literal>
struct my_template {...};
and have calls to func_literal within my_template compile to callq <immediate address>.
Is there a facility in C++ for this, or a work around to achieve the same effect? If not, why not (e.g. some cataclysmic side effects)? How about C++0x or another language?
| If you use a function pointer type in your template and instantiate it with a fixed function, then the compiler should use a direct call for that function pointer call.
|
2,878,259 | 2,878,320 | Texture coordintes for a polygon and a square texture | basically I have a texture. I also have a lets say octagon (or any polygon). I find that octagon's bounding box. Let's say my texture is the size of the octagon's bounding box. How could I figure out the texture coordinates so that the texture maps to it. To clarify, lets say you had a square of tin foil and cut the octagon out you'd be left with a tin foil textured polygon.I'm just not sure how to figure it out for an arbitrary polygon. Thanks
| See Texture mapping an NGon?.
|
2,878,401 | 2,878,687 | C++ class is not recognizing string data type | I'm working on a program from my C++ textbook, and this this the first time I've really run into trouble. I just can't seem to see what is wrong here. Visual Studio is telling me Error: identifier "string" is undefined.
I separated the program into three files. A header file for the class specification, a .cpp file for the class implementation and the main program file. These are the instructions from my book:
Write a class named Car that has the following member variables:
year. An int that holds the car's model year.
make. A string that holds the make of the car.
speed. An int that holds the car's current speed.
In addition, the class should have the following member functions.
Constructor. The constructor should accept the car's year and make as arguments and assign these values to the object's year and make member variables. The constructor should initialize the speed member variable to 0.
Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an object's year, make and speed member variables.
There are more instructions, but they are not necessary to get this part to work.
Here is my source code:
// File Car.h -- Car class specification file
#ifndef CAR_H
#define CAR_H
class Car
{
private:
int year;
string make;
int speed;
public:
Car(int, string);
int getYear();
string getMake();
int getSpeed();
};
#endif
// File Car.cpp -- Car class function implementation file
#include "Car.h"
// Default Constructor
Car::Car(int inputYear, string inputMake)
{
year = inputYear;
make = inputMake;
speed = 0;
}
// Accessors
int Car::getYear()
{
return year;
}
string Car::getMake()
{
return make;
}
int Car::getSpeed()
{
return speed;
}
// Main program
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
int main()
{
}
I haven't written anything in the main program yet, because I can't get the class to compile. I've only linked the header file to the main program. Thanks in advance to all who take the time to investigate this problem for me.
| You have forgotten to #include the string header and you need to fully qualify your usage of string to std::string, the amended code should be.
// File Car.h -- Car class specification file
#ifndef CAR_H
#define CAR_H
#include <string>
class Car
{
private:
int year;
std::string make;
int speed;
public:
Car(int, string);
int getYear();
std::string getMake();
int getSpeed();
};
#endif
// File Car.cpp -- Car class function implementation file
#include "Car.h"
// Default Constructor
Car::Car(int inputYear, std::string inputMake)
{
year = inputYear;
make = inputMake;
speed = 0;
}
// Accessors
int Car::getYear()
{
return year;
}
You could put using namespace std; at the top of Car.cpp and that would let you use string without the std:: qualifier in that file. However DON'T put one of these in the header because it is very bad mojo.
As a note you should always include everything that the class declaration needs in the header before the class body, you should never rely on a client source file including a file (like <string>) before it includes your header.
With regard to this part of your task:
Constructor. The constructor should
accept the car's year and make as
arguments and assign these values to
the object's year and make member
variables. The constructor should
initialize the speed member variable
to 0.
The best practice is to use an initializer list in the constructor, like so:
// Default Constructor
Car::Car(int inputYear, string inputMake)
: year(inputYear),
make(inputMake),
speed(0)
{
}
|
2,878,933 | 2,879,122 | Unable to create unmanaged object using new keyword in managed C++ | I've created a class with a boost::unordered_map as a member,
Linkage.h
#ifndef LINKAGE_H
#define LINKAGE_H
#include <boost/unordered_map.hpp>
class Linkage
{
private:
boost::unordered_map<int, int> m_IOMap;
public:
....
};
Linkage.cpp
#include "stdafx.h"
... // methods
and in the managed side of C++,
I try to create the pointer of the obj:
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
Linkage* m_pLink = new Linkage();
.....
}
However this produces errors:
Error 4 error LNK2005: "private: static unsigned int const boost::detail::type_with_alignment_imp<4>::found" (?found@?$type_with_alignment_imp@$03@detail@boost@@$$Q0IB) already defined in Proj_Test.obj Linkage.obj
.....
Error 7 fatal error LNK1169: one or more multiply defined symbols found
Could anyone explain to me pls?
Thanks.
| Eventually this works when I explicitly instantiate it inside the constructor:
#include "stdafx.h"
Linkage::Linkage()
{
template boost::unordered_map<int, int>;
}
|
2,879,055 | 2,879,073 | How to think in Python after working in C++? | I'm brand new to Python and trying to learn it by replicating the following C++ function into python
// determines which words in a vector consist of the same letters
// outputs the words with the same letters on the same line
void equivalentWords(vector <string> words, ofstream & outFile) {
outFile << "Equivalent words\n";
// checkedWord is parallel to the words vector. It is
// used to make sure each word is only displayed once.
vector <bool> checkedWord (words.size(), false);
for(int i = 0; i < words.size(); i++) {
if (!checkedWord[i]){
outFile << " ";
for(int j = i; j < words.size(); j++){
if(equivalentWords(words[i], words[j], outFile)) {
outFile << words[j] << " ";
checkedWord[j] = true;
}
}
outFile << "\n";
}
}
}
In my python code (below), rather than having a second vector, I have a list ("words") of lists of a string, a sorted list of the chars in the former string (because strings are immutable), and a bool (that tells if the word has been checked yet). However, I can't figure out how to change a value as you iterate through a list.
for word, s_word, checked in words:
if not checked:
for word1, s_word1, checked1 in words:
if s_word1 == s_word:
checked1 = True # this doesn't work
print word1,
print ""
Any help on doing this or thinking more "Pythony" is appreciated.
| Keeping things simple, this is O(N) complexity and should be sufficient if you don't have GBs of word data. Note that set() and dict() basically is a hashed index (free and builtin!).
index = {}
for word, s_word in words:
index[s_word] = index.get(s_word, []) + [word]
for similar_words in index.values():
print ' '.join(similar_words)
Don't know what you are using it for, but it might be of interest to you that in python 2.7 a Counter class was introduced in the collections module.
If you really want to keep your algorithm and update a boolean list (which you don't because that algorithm would do inefficient double loops), you would do it like this:
checked = [False] * len(words)
for i, (word, word_s) in enumerate(words):
if checked[i]:
continue
for j, (other, other_s) in enumerate(words[i:]):
if word_s == other_s:
print other,
checked[i+j] = True
print
|
2,879,145 | 2,879,164 | C++ performance, for versus while | In general (or from your experience), is there difference in performance between for and while loops?
What if they are doubly/triply nested?
Is vectorization (SSE) affected by loop variant in g++ or Intel compilers?
Thank you
| Here is a nice paper on the subject.
|
2,879,222 | 2,879,263 | Using a macro for fstream file input as part of a class | I have a class that processes a file, and as part of the constructor with one argument I want to input a file using fstream.
I basically want it do something like this
class someClass{
public:
someClass(char * FILENAME)
{
fstream fileToProcess;
fileToProcess.open(<FILENAME>, fstream::in | fstream::out | fstream::app);
}
};
I want to pass the filename in as an argument to the class constructor, and then the class someClass will access it with fstream.
| You don't need a macro, and you don't have to explicitly call open.
using std::fstream;
class someClass
{
fstream fileToProcess;
public:
someClass(char * filename)
: fileToProcess(filename, fstream::in | fstream::out | fstream::app)
{
}
};
|
2,879,438 | 2,928,462 | Integrate code generation with eclipse c++ build | I am using Eclipse for C++ development on windows. I have also written a code generator that take an xml file and produces several C++ files. The project I am working on is currently setup to use the internal builder. What I would like to do is to run the code generator as part of the build process.
My problem is that I haven't been able to find a way to make Eclipse identify that the files are present (or have been updated) without 'Refeshing' the project. So although I can run the code generator as a pre-build step, the files generated aren't guaranteed to be included in the build.
Does anybody know whether there is a way to make Eclipse do a refresh after the pre-build step or something to that effect, using the internal builder?
Thanks
| You can add a Builder to your project.
|
2,879,537 | 2,879,610 | How to use fgets if you don't know the number of characters to be read? | I need to read a file and send the text from it to a string so I can parse it. However, the program won't know exactly how long the file is, so what would I do if I wanted to use fgets(), or is there a better alternative?
Note:
char *fgets(char *str, size_t num, FILE *stream);
| Don't forget that fgets() reads a line at a time, subject to having enough space.
Humans seldom write lines longer than ... 80, 256, pick a number ... characters. POSIX suggests a line length of 4096. So, I usually use:
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp))
{
...process line...
}
If you are worried that someone might provide more than 4K of data in a single line (and a machine generated file, such as HTML or JSON, might contain that), then you have to decide what to do next. You can do any of the following (and there are likely some other options I've not mentioned):
Process the over-long lines in bits without assuming that there was a newline in between.
Allocate memory for a longer line (say 8K to start with), copy the initial 4K into the allocated buffer, and read more data into the second half of the buffer, iterating until you find the end of line.
Use the POSIX 2008 function getline() which is available on Linux. It does memory allocation for you.
|
2,879,548 | 2,879,851 | Is it appropriate to set a value to a "const char *" in the header file | I have seen people using 2 methods to declare and define char *.
Medhod 1: The header file has the below
extern const char* COUNTRY_NAME_USA = "USA";
Medhod 2:
The header file has the below declaration:
extern const char* COUNTRY_NAME_USA;
The cpp file has the below definition:
extern const char* COUNTRY_NAME_USA = "USA";
Is method 1 wrong in some way ?
What is the difference between the two ?
I understand the difference between "const char * const var" , and "const char * var". If in the above methods if a "const char * const var" is declared and defined in the header as in method 1 will it make sense ?
| The first method is indeed wrong, since it makes a definition of an object COUNTRY_NAME_USA with external linkage in the header file. Once that header file gets included into more than one translation unit, the One Definition Rule (ODR) gets violated. The code will fail to compile (more precisely, it will fail to link).
The second method is the correct one. The keyword extern is optional in the definition though, i.e. in the cpp file you can just do
const char* COUNTRY_NAME_USA = "USA"
assuming the declaration from the header file precedes this definition in this translation unit.
Also, I'd guess that since the object name is capitalized, it is probably intended to be a constant. If so, then it should be declared/defined as const char* const COUNTRY_NAME_USA (note the extra const).
Finally, taking that last detail into account, you can just define your constant as
const char* const COUNTRY_NAME_USA = "USA"; // no `extern`!
in the header file. Since it is a constant now, it has internal linkage by default, meaning that there is no ODR violation even if the header file is included into several translation units. In this case you get a separate COUNTRY_NAME_USA lvalue in each translation unit (while in extern method you get one for the entire program). Only you know what you need in your case .
|
2,879,555 | 2,879,561 | C++ Standard Library: How to write wrappers for cout, cerr, cin and endl? | I do not like using namespace std, but I am also tired of having to type std:: in front of every cout, cin, cerr and endl. So, I thought of giving them shorter new names like this:
// STLWrapper.h
#include <iostream>
#include <string>
extern std::ostream& Cout;
extern std::ostream& Cerr;
extern std::istream& Cin;
extern std::string& Endl;
// STLWrapper.cpp
#include "STLWrapper.h"
std::ostream& Cout = std::cout;
std::ostream& Cerr = std::cerr;
std::istream& Cerr = std::cin;
std::string _EndlStr("\n");
std::string& Endl = _EndlStr;
This works. But, are there any problems in the above which I am missing? Is there a better way to achieve the same?
| Why not
using std::cin;
using std::cout;
and so on? Then in your code you can use cin, cout, and so on, without accidentally injecting all of the rest of the std namespace into your code.
|
2,879,665 | 2,880,263 | GTKMM/C++ Window Event on losing/regaining focus? | How can I call a function whenever my GTKMM app loses or regains focus?
| Connect handlers to the window's focus-in-event and focus-out-event.
|
2,880,248 | 2,880,433 | std::string.resize() and std::string.length() | I'm relatively new to C++ and I'm still getting to grips with the C++ Standard Library. To help transition from C, I want to format a std::string using printf-style formatters. I realise stringstream is a more type-safe approach, but I find myself finding printf-style much easier to read and deal with (at least, for the time being). This is my function:
using namespace std;
string formatStdString(const string &format, ...)
{
va_list va;
string output;
size_t needed;
size_t used;
va_start(va, format);
needed = vsnprintf(&output[0], 0, format.c_str(), va);
output.resize(needed + 1); // for null terminator??
va_end(va);
va_start(va, format);
used = vsnprintf(&output[0], output.capacity(), format.c_str(), va);
// assert(used == needed);
va_end(va);
return output;
}
This works, kinda. A few things that I am not sure about are:
Do I need to make room for a null terminator, or is this unnecessary?
Is capacity() the right function to call here? I keep thinking length() would return 0 since the first character in the string is a '\0'.
Occasionally while writing this string's contents to a socket (using its c_str() and length()), I have null bytes popping up on the receiving end, which is causing a bit of grief, but they seem to appear inconsistently. If I don't use this function at all, no null bytes appear.
| With the current standard (the upcomming standard differs here) there is no guarantee that the internal memory buffer managed by the std::string will be contiguous, or that the .c_str() method returns a pointer to the internal data representation (the implementation is allowed to generate a contiguous read-only block for that operation and return a pointer into it. A pointer to the actual internal data can be retrieved with the .data() member method, but note that it also returns a constant pointer: i.e. it is not intended for you to modify the contents. The buffer return by .data() it is not necessarily null terminated, the implementation only needs to guarantee the null termination when c_str() is called, so even in implementations where .data() and .c_str() are called, the implementation can add the \0 to the end of the buffer when the latter is called.
The standard intended to allow rope implementations, so in principle it is unsafe to do what you are trying, and from the point of view of the standard you should use an intermediate std::vector (guaranteed contiguity, and there is a guarantee that &myvector[0] is a pointer to the first allocated block of the real buffer).
In all implementations I know of, the internal memory handled by std::string is actually a contiguous buffer and using .data() is undefined behavior (writting to a constant variable) but even if incorrect it might work (I would avoid it). You should use other libraries that are designed for this purpose, like boost::format.
About the null termination. If you finally decide to follow the path of the undefined... you would need to allocate extra space for the null terminator, since the library will write it into the buffer. Now, the problem is that unlike C-style strings, std::strings can hold null pointers internally, so you will have to resize the string down to fit the largest contiguous block of memory from the beginning that contains no \0. That is probably the issue you are finding with spurious null characters. This means that the bad approach of using vsnprintf(or the family) has to be followed by str.resize( strlen( str.c_str() ) ) to discard all contents of the string after the first \0.
Overall, I would advice against this approach, and insist in either getting used to the C++ way of formatting, using third party libraries (boost is third party, but it is also the most standard non-standard library), using vectors or managing memory like in C... but that last option should be avoided like the plague.
// A safe way in C++ of using vsnprintf:
std::vector<char> tmp( 1000 ); // expected maximum size
vsnprintf( &tmp[0], tmp.size(), "Hi %s", name.c_str() ); // assuming name to be a string
std::string salute( &tmp[0] );
|
2,880,578 | 2,880,603 | pass by const reference of class | void foo(const ClassName &name)
{
...
}
How can I access the method of class instance name?
name.method() didn't work. then I tried:
void foo(const ClassName &name)
{
ClassName temp = name;
... ....
}
I can use temp.method, but after foo was executed, the original name screwed up, any idea?
BTW, the member variable of name didn't screwed up, but it was the member variable of subclass of class screwed up.
| If I understand you correctly, you want to call name.method() inside foo() and the compiler doesn't let you. Is ClassName::method() a non-const method by any chance? Since name is declared as a const parameter to foo(), you can only call const functions on it.
Update: if ClassName::method() is non-const, but does not actually change state, the best would be of course to make it const. In case you can't for some reason, I see the following ways:
(the obvious way, as @Naveen pointed out - thanks :-) declare name as a non-const method parameter.
make a non const copy of name, and call method on it - as you actually did. However, this works only if the assignment operator and/or copy constructor is properly implemented for ClassName. However, you write "after foo was executed, the original name screwed up", which is a very vague description, but it can be interpreted so that copying did have some unwanted side effects on name, which suggests that those functions are not implemented correctly or at all.
(the nasty way) cast away constness with const_cast - this should really be a last resort, and only if you are sure that ClassName::method() does not actually change any state.
Update2, to @AKN's comment - example of casting away constness:
void foo(const ClassName &name)
{
ClassName& temp = const_cast<ClassName&>(name);
... ....
}
|
2,880,670 | 2,880,743 | Can I add Boost source+header files to my own (Open Source) project? | Is it allowed by the Boost License to just add the source code of the stuff I need to my project (accompanied by the license of course?). I couldn't find any "descriptive" confirmation. I would have seperate Include/boost and Source/boost directories for easy access.
PS: Seeing as boost::filesystem is going into C++0x TR2, and lambda, regex and whatnot are already in c++0x TR1, I don't see any reason to be juggling with C functions like realpath, getcwd and the like. They don't work well anyways...
UPDATE: I'm adding the required files "one-by-one" folder by folder, but the amount is gigantic. Maybe it's better to include the full boost dist....
| Yes you can do that. The license is very liberal. The only condition is that if you redistribute your software in source form you need to include a complete copy of the license.
|
2,880,852 | 2,880,872 | How to simulate Func<T1, T2, TResult> in C++? | In C#, I use Func to replace Factories. For example:
class SqlDataFetcher
{
public Func<IConnection> CreateConnectionFunc;
public void DoRead()
{
IConnection conn = CreateConnectionFunc(); // call the Func to retrieve a connection
}
}
class Program
{
public void CreateConnection()
{
return new SqlConnection();
}
public void Main()
{
SqlDataFetcher f = new SqlDataFetcher();
f.CreateConnectionFunc = this.CreateConnection;
...
}
}
How can I simulate the code above in C++?
| Use either std::tr1::function<IConnection*()> or boost::function<IConnection*()> as the equivalent of Func<IConnection>.
When you come to assign the function, you'll need to bind a object and a function together;
f.CreateConnectionFunc = this.CreateConnection;
would become
f.CreateConnectionFunc = std::tr1::bind(&Program::CreateConnection,this);
(That assumes CreateConnection is not a static function - your example code doesn't get its statics correct, so it's difficult to tell exactly what you meant).
|
2,880,881 | 2,880,904 | Unresolved symbol when inheriting interface | It's late at night here and I'm going crazy trying to solve a linker error.
If I have the following abstract interface:
class IArpPacketBuilder
{
public:
IArpPacketBuilder(const DslPortId& aPortId);
virtual ~IArpPacketBuilder();
// Other abstract (pure virtual methods) here...
};
and I instantiate it like this:
class DummyArpPacketBuilder
: public IArpPacketBuilder
{
public:
DummyArpPacketBuilder(const DslPortId& aPortId)
: IArpPacketBuilder(aPortId) {}
~DummyArpPacketBuilder() {}
};
why am I getting the following error when linking?
Unresolved symbol references:
IArpPacketBuilder::IArpPacketBuilder(DslPortId const&):
ppc603_vxworks/_arpPacketQueue.o
IArpPacketBuilder::~IArpPacketBuilder():
ppc603_vxworks/_arpPacketQueue.o
typeinfo for IArpPacketBuilder:
ppc603_vxworks/_arpPacketQueue.o
*** Error code 1
IArpPacketBuilder is an abstract interface, so as long as I define the constructors and destructions in the concrete (derived) interface, I should be fine, no? Well it appears not.
| You have only declared the constructor and destructor of IArpPacketBuilder, not defined them. The linker needs the definitions too. Note that C++ has no concept of abstract interface - IArpPacketBuilder is a plain old class which happens to contain some pure virtual methods, thus making its direct instantiation impossible.
So the simplest solution is to provide inline implementations:
class IArpPacketBuilder
{
public:
IArpPacketBuilder(const DslPortId& aPortId) {}
virtual ~IArpPacketBuilder() {}
// Other abstract (pure virtual methods) here...
};
You can also make the destructor pure virtual, but even so, you still need to provide a definition for it, e.g.
class IArpPacketBuilder
{
public:
IArpPacketBuilder(const DslPortId& aPortId) {}
virtual ~IArpPacketBuilder() = 0;
// Other abstract (pure virtual methods) here...
};
IArpPacketBuilder::~IArpPacketBuilder() {}
|
2,880,903 | 2,881,987 | Simple string parsing with C++ | I've been using C++ for quite a long time now but nevertheless I tend to fall back on scanf when I have to parse simple text files. For example given a config like this (also assuming that the order of the fields could vary):
foo: [3 4 5]
baz: 3.0
I would write something like:
char line[SOME_SIZE];
while (fgets(line, SOME_SIZE, file)) {
int x, y, z;
if (3 == sscanf(line, "foo: [%d %d %d]", &x, &y, &z)) {
continue;
}
float w;
if (1 == sscanf(line, "baz: %f", &w)) {
continue;
}
}
What's the most concise way to achieve this in C++? Whenever I try I end up with a lot of scaffolding code.
| This is a try using only standard C++.
Most of the time I use a combination of std::istringstream and std::getline (which can work to separate words) to get what I want. And if I can I make my config files look like:
foo=1,2,3,4
which makes it easy.
text file is like this:
foo=1,2,3,4
bar=0
And you parse it like this:
int main()
{
std::ifstream file( "sample.txt" );
std::string line;
while( std::getline( file, line ) )
{
std::istringstream iss( line );
std::string result;
if( std::getline( iss, result , '=') )
{
if( result == "foo" )
{
std::string token;
while( std::getline( iss, token, ',' ) )
{
std::cout << token << std::endl;
}
}
if( result == "bar" )
{
//...
}
}
|
2,880,912 | 2,884,119 | performance: is it better to read all files once, or use b::fs functions over and over again? | I'm conflicted between a "read once, use memory+pointers to files" and a "read when necessary" approach. The latter is of course much easier (no additional classes needed to store the whole dir structure), but IMO it is slower? I'm trying to list the filenames and relative paths (so the compiler can do with them what it needs to).
A little clarification: I'm writing a simple build system, that read a project file, checks if all files are present, and runs some compile steps. The file tree is static, so the first option doesn't need to be very dynamic and only needs to be built once every time the program is run. Thanks
| You can safely assume that the operating system will cache the directory contents anyway, so that access through file system APIs will come down to memory operations.
So the answer to your question "is it faster?" is likely "No, not measurably".
OTOH, consider that a directories contents can change over time, even in very short time. Thus, reading directory content eagerly or lazyily is not so much a question of speed, but of semantics. It may be that you find that you must/must not read the entire directory, depending on what you are doing.
|
2,880,981 | 2,880,991 | Get a char from a CString | I have created a function that has as input a char szMyChar; (using it in a switch statement).
Now I have a CString having just a char, lets say CString strString = "A";
An option to call the function could be:
if (strString == "A")
CallMyFunc('A');
though it is clumsy. I tried atoi (returns 0) and casting though neither works.
Any ideas?
Thanks,
Sun
| Either I'm not quite understanding what you're asking, or it's as simple as:
CallMyFunc(strString[0]);
See Accessing Individual Characters in a CString for more information.
|
2,881,102 | 2,881,234 | Is the use of union in this matrix class completely safe? | Unions aren't something I've used that often and after looking at a few other questions on them here it seems like there is almost always some kind of caveat where they might not work. Eg. structs possibly having unexpected padding or endian differences.
Came across this in a math library I'm using though and I wondered if it is a totally safe usage. I assume that multidimensional arrays don't have any extra padding and since the type is the same for both definitions they are guaranteed to take up exactly the same amount of memory?
template<typename T> class Matrix44T
{
...
union
{
T M[16];
T m[4][4];
} m;
};
Are there any downsides to this setup? Would the order of definition make any difference to how this works?
| Although I do exactly the same in my Matrix-class I think this is implementation dependent, reading the standard to the letter:
Standard 9.5.1:
In a union, at most one of the data
members can be active at any time,
that is, the value of at most one of
the data members can be stored in a
union at any time. [Note: one special
guarantee is made in order to simplify
the use of unions: If a POD-union
contains several POD-structs that
share a common initial sequence (9.2),
and if an object of this POD-union
type contains one of the POD-structs,
it is permitted to inspect the common
initial sequence of any of POD-struct
members; see 9.2. ]
The question then is do m and M share a common initial sequence, to answer this we look at 9.2/15:
Two POD-union (clause 9) types are
layout-compatible if they have the
same number of nonstatic data members,
and corresponding nonstatic data
members (in any order) have
layout-compatible types (3.9).
After reading this the answer seems to be, no m and M are not layout-compatible in the strict sense of the word.
In practice I think this will work fine on all compilers though.
|
2,881,184 | 2,881,212 | How to find where program crashed | I have a program that crashes (attempting to read a bad memory address) while running the "release" version but does not report any problems while running the "debug" version in the visual studio debugger.
When the program crashes the OS asks if I'd like to open up the debugger, and if I say yes then I see an arrow pointing to where I am in a listing of some assembler which I am not skilled enough to read properly (I learned 6502 assembler 30 years ago). Is there any way for my to determine where in my sourcecode the offending memory read was located?
| You need to build your program with Debug info enabled (which you can do even for release builds) and that debug info (*.pdb files) must be accessible to the debugger (just copy it beside the executable).
The VS should be able to show you the source, stack and everything else.
|
2,881,239 | 2,881,415 | How can I avoid encoding mixups of strings in a C/C++ API? | I'm working on implementing different APIs in C and C++ and wondered what techniques are available for avoiding that clients get the encoding wrong when receiving strings from the framework or passing them back. For instance, imagine a simple plugin API in C++ which customers can implement to influence translations. It might feature a function like this:
const char *getTranslatedWord( const char *englishWord );
Now, let's say that I'd like to enforce that all strings are passed as UTF-8. Of course I'd document this requirement, but I'd like the compiler to enforce the right encoding, maybe by using dedicated types. For instance, something like this:
class Word {
public:
static Word fromUtf8( const char *data ) { return Word( data ); }
const char *toUtf8() { return m_data; }
private:
Word( const char *data ) : m_data( data ) { }
const char *m_data;
};
I could now use this specialized type in the API:
Word getTranslatedWord( const Word &englishWord );
Unfortunately, it's easy to make this very inefficient. The Word class lacks proper copy constructors, assignment operators etc.. and I'd like to avoid unnecessary copying of data as much as possible. Also, I see the danger that Word gets extended with more and more utility functions (like length or fromLatin1 or substr etc.) and I'd rather not write Yet Another String Class. I just want a little container which avoids accidental encoding mixups.
I wonder whether anybody else has some experience with this and can share some useful techniques.
EDIT: In my particular case, the API is used on Windows and Linux using MSVC 6 - MSVC 10 on Windows and gcc 3 & 4 on Linux.
| You could pass arround a std::pair instead of a char*:
struct utf8_tag_t{} utf8_tag;
std::pair<const char*,utf8_tag_t> getTranslatedWord(std::pair<const char*,utf8_tag_t> englishWord);
The generated machine code should be identical on a decent modern compiler that uses the empty base class optimization for std::pair.
I don't bother with this though. I'd just use char*s and document that the input has to be utf8. If the data could come from an untrusted source, you're going to have to check the encoding at runtime anyway.
|
2,881,268 | 2,881,314 | How a member func can know *programmatically* the 'name of the object' that is calling it? | Let say we have a class MyClass that has and a memberfunc().
An object is created for this MyClass, say ObjA.
i.e MyClass ObjA;
ObjA calls memberfunc().
Can we get this name 'ObjA' inside memberfunc() programatically?
Note: I know how to get the type of the object, i.e 'MyClass', using RTTI (Run-Time Type Identification), the same is also explained by radman below.
EDIT:
If this is NOT POSSIBLE in c++, Is it possible in any other programming language?
EDIT2
Made some modification to the question as few were unable to interpret.
| There are several issues here:
Objects don't call anything, code does.
Objects don't have a name. An object is usually assigned to a variable, often to more than one variable, often to no variable at all, such as an array element.
Getting access to the call stack might give you some idea of the calling class that owns the code that called you, but even this usually requires a level of introspection that goes beyond the reflection facilities of most languages.
Python is a notable exception. It can give you the stack to walk and figure out lots of interesting things. C++ won't.
I have seen C++ libraries that crack open the stack (this is very non-portable, by the way) and thus give code the ability to figure stuff out like, "Who called me?" but I haven't used that stuff for years.
|
2,881,305 | 2,881,463 | Internal class and access to external members | I have question with this same title here but now as I'll present in code below this seems to behave in the opposite way to the way explained to me in my first question with the same title. Ok code:
class LINT_rep
{
private:
char* my_data_; //stores separately every single digit from a number
public:
class Iterator:public iterator<bidirectional_operator_tag,char>
{
private:
char* myData_
public:
Iterator(const LINT_rep&);
};
};
#include "StdAfx.h"
#include "LINT_rep.h"
LINT_rep::Iterator::Iterator(const LINT_rep& owner):myData_(nullptr)
{
myData_ = owner.my_data_; /*
HERE I'M ACCESSING my_data WHICH IS PRIVATE AND THIS
CODE COMPILES ON VS2010 ULTIMATE BUT IT SHOULDN'T
BECAUSE my_data IS PRIVATE AND OTHER CLASS SHOULDN'T
HAVE ACCESS TO IT'S PRIVATE MEMB. AS EXPLAINED TO ME IN
QUESTION TO WHICH I;VE PROVIDED LINK. */
}
Question in the code. Thanks.
| Access rights for nested classes to members of the enclosing classes are changing in the upcoming C++0x standard. In the current standard, 11.8 says:
The members of a nested class have no special access to members of an enclosing class
In the draft for C++0x, this changes to
A nested class is a member and as such has the same access rights as any other member
Some compilers are adopting the new access rules; from your question, I guess VS2010 does, and I know from experience that GCC has done for some time.
|
2,881,454 | 2,881,745 | "Unhandled exception"/"Access violation writing location" error with referenced array pointers | I'm trying to fill a pointer matrix with values from a text file. It's a double pointer to a simple struct with 2 ints, time and tons.
void get_changes(change** &c){
ifstream file("change_data_time.prn"); //data file, time only, size is the same as tons
string line, var; //string placeholders for the getlines
int i, j; // count variables
int count=0;
while(getline(file, line))
count++; //counting matrix size (matrix is square)
c = new change *[count]; //resize pointers with matrix size
for(i=0; i<count; i++)
c[i] = new change[count];
file.clear();
file.close();
file.open("change_data_time.prn"); //reset data stream to read values
i = 0; //reset counting variables
j = 0;
while(getline(file, line)){
stringstream sline(line); //getlines only read streams and output to strings
while(getline(sline, var, '\t')){ //separate with tabs
stringstream svar(var);
svar >> c[i][j].time; //BREAKS HERE
j++;
}
i++;
}
}
It breaks when i actually try to add the values to the pointer array and i can't understand why. It breaks on the first run of the while loops.
Thanks in advance for any suggestions.
| I would rewrite the code to get rid of the manual memory management around change** c.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
struct MaxtrixElement
{
double time;
};
std::istream& operator >> (std::istream& in, MaxtrixElement& dest)
{
double d;
// error checking ommitted
in >> d;
dest.time = d;
return in;
}
std::ostream& operator << (std::ostream& os, const MaxtrixElement& e)
{
os << e.time;
return os;
}
typedef std::vector<MaxtrixElement> Line;
typedef std::vector<Line> Matrix;
void foobar(std::istream& is, Matrix& dest)
{
std::string ln;
while(std::getline(is, ln))
{
std::stringstream lnStream(ln);
Line l;
std::copy(std::istream_iterator<MaxtrixElement>(lnStream),
std::istream_iterator<MaxtrixElement>(),
std::back_inserter(l));
dest.push_back(l);
}
}
int main()
{
Matrix m;
foobar(std::cin, m);
for(Matrix::const_iterator it=m.begin(); it!=m.end(); ++it)
{
std::copy(it->begin(), it->end(), std::ostream_iterator<MaxtrixElement>(std::cout, ", "));
std::cout << '\n';
}
}
|
2,881,517 | 2,881,537 | Uses for the capacity value of a string | In the C++ Standard Library, std::string has a public member function capacity() which returns the size of the internal allocated storage, a value greater than or equal to the number of characters in the string (according to here). What can this value be used for? Does it have something to do with custom allocators?
| You are more likely to use the reserve() member function, which sets the capacity to at least the supplied value.
The capacity() member function itself might be used to avoid allocating memory. For instance, you could recycle used strings through a pool, and put each one in a different size bucket based on its capacity. A client of the pool could then ask for a string that already has some minimum capacity.
|
2,881,624 | 2,882,077 | C++ - Totally suspend windows application | I am developing a simple WinAPI application and started from writing my own assertion system.
I have a macro defined like ASSERT(X) which would make pretty the same thing as assert(X) does, but with more information, more options and etc.
At some moment (when that assertion system was already running and working) I realized there is a problem.
Suppose I wrote a code that does some action using a timer and (just a simple example) this action is done while handling WM_TIMER message. And now, the situation changes the way that this code starts throwing an assert. This assert message would be shown every TIMER_RESOLUTION milliseconds and would simply flood the screen.
Options for solving this situation could be:
1) Totally pause application running (probably also, suspend all threads) when the assertion messagebox is shown and continue running after it is closed
2) Make a static counter for the shown asserts and don't show asserts when one of them is already showing (but this doesn't pause application)
3) Group similiar asserts and show only one for each assert type (but this also doesn't pause application)
4) Modify the application code (for example, Get / Translate / Dispatch message loop) so that it suspends itself when there are any asserts. This is good, but not universal and looks like a hack.
To my mind, option number 1 is the best. But I don't know any way how this can be achieved. What I'm seeking for is a way to pause the runtime (something similiar to Pause button in the debugger). Does somebody know how to achieve this?
Also, if somebody knows an efficient way to handle this problem - I would appreciate your help. Thank you.
| It is important to understand how Windows UI programs work, to answer this question.
At the core of the Windows UI programming model is of course "the message" queue". Messages arrive in message queues and are retrieved using message pumps. A message pump is not special. It's merely a loop that retrieves one message at a time, blocking the thread if none are available.
Now why are you getting all these dialogs? Dialog boxes, including MessageBox also have a message pump. As such, they will retrieve messages from the message queue (It doesn't matter much who is pumping messages, in the Windows model). This allows paints, mouse movement and keyboard input to work. It will also trigger additional timers and therefore dialog boxes.
So, the canonical Windows approach is to handle each message whenever it arrives. They are a fact of life and you deal with them.
In your situation, I would consider a slight variation. You really want to save the state of your stack at the point where the assert happened. That's a particularity of asserts that deserves to be respected. Therefore, spin off a thread for your dialog, and create it without a parent HWND. This gives the dialog an isolated message queue, independent of the original window. Since there's also a new thread for it, you can suspend the original thread, the one where WM_TIMER arrives.
|
2,882,014 | 2,882,021 | Is there any way to convert C++ program into ASP.NET? | Is there any way to convert C++ program into ASP.NET?
| No there is not.
You have some options though:
You can create a managed C++ / CLI DLL from your C++ code.
You can create a C++ Win32 DLL and use p/invoke to import the DLL functions into your ASP.NET page.
Re-write your code in C# or another .Net language.
|
2,882,062 | 2,882,145 | Why does compiler complain when I try to convert to a base-class? | BaseClass.h
class BaseClass
{
...
};
SubClass.h
#include "BaseClass.h"
class SubClass : public BaseClass
{
...
};
MyApp.h
class BaseClass;
class SubClass;
class MyApp
{
SubClass *pObject;
BaseClass *getObject()
{
return pObject;
}
};
I get a compiler error: error C2440: 'return' : cannot convert from 'SubClass *' to 'BaseClass *'
Why doesn't it work, surely you can automatically convert to a base-class without any casting?
| In "MyApp.h", you only have forward declarations of the classes, so it's not known that one derives from the other. You will need to include the "SubClass.h" before the body of getObject(); either include it from "MyApp.h", or move the body of getObject() into a source file and include it from there.
|
2,882,068 | 2,882,083 | Do you recommend Enabling Code Analysis for C/C++ on Build? | I'm using Visual Studio 2010, and in my C++/CLI project there are two Code Analysis settings:
Enable Code Analysis on Build
Enable Code Analysis for C/C++ on Build
My question is about the second setting.
I've enabled it and it takes a long time to run and it doesn't find much.
Do you recommend enabling this feature? Why?
| Never did anything for me. In theory, it's supposed to help catch logical errors, but I've never found it to report anything.
|
2,882,177 | 2,882,371 | C++ - Dialog box question | This is a more concrete question that is connected with my previous one.
I have an application that uses a timer. The code is written the way the my WM_TIMER handler call a DialogBoxParam(...) with some custom message handler (let's call it DlgProc).
This is done somewhat the following way:
case WM_TIMER:
{
// Routine, that displays a special message box
DisplayMessageBox(...);
return 0;
}
Now, if I make DlgProc handle the messages like this (see the code), this would result in tons of dialog boxes (one per WM_TIMER call).
switch (msg)
{
case WM_INITDIALOG:
// (...)
return TRUE;
case WM_COMMAND:
// (...)
return TRUE;
return FALSE;
}
But if I add a dummy WM_PAINT handler (return TRUE;) to my DlgProc, this results in exactly one shown DialogBox and 100% CPU load (that's because I receive tons of WM_PAINT messages).
Q:
What can be done here if I want my application to show exactly ONE dialog box and have no CPU load for WM_PAINT processing? (I mean like, have behaviour similiar to draw unique dialog box and fully pause the parent window).
Also it would be great if someone explains what actually happens in this situation and why do I receive gazillions of WM_PAINT messages to my dialog box and why their processing (with return TRUE) results in preventing the other dialog boxes creation.
Thank you.
| 1) You should disable the timer after the first WM_TIMER signal is caught if you want to show only one single dialog box. You can do this using KillTimer().
2) Windows wants to keep the GUI up-to-date. Whenever a region on the screen should be updated, it is invalidated using InvalidateRect or InvalidateRgn. Now, for every "invalid" screen part, WM_PAINT is called in order to make in "valid" again.
If you don't do it (or just parts of it), Windows will call WM_PAINT again ... and again. One way is to call ValidateRect. In many cases BeginPaint() and EndPaint() are used to do the job.
3) Maybe most important: you should not just return FALSE! Try DefWindowProc() for windows and DefDlgProc() for dialogs. They will also take care of WM_PAINT appropriately.
|
2,882,706 | 2,882,819 | How can I write a power function myself? | I was always wondering how I can make a function which calculates the power (e.g. 23) myself. In most languages these are included in the standard library, mostly as pow(double x, double y), but how can I write it myself?
I was thinking about for loops, but it think my brain got in a loop (when I wanted to do a power with a non-integer exponent, like 54.5 or negatives 2-21) and I went crazy ;)
So, how can I write a function which calculates the power of a real number? Thanks
Oh, maybe important to note: I cannot use functions which use powers (e.g. exp), which would make this ultimately useless.
| Negative powers are not a problem, they're just the inverse (1/x) of the positive power.
Floating point powers are just a little bit more complicated; as you know a fractional power is equivalent to a root (e.g. x^(1/2) == sqrt(x)) and you also know that multiplying powers with the same base is equivalent to add their exponents.
With all the above, you can:
Decompose the exponent in a integer part and a rational part.
Calculate the integer power with a loop (you can optimise it decomposing in factors and reusing partial calculations).
Calculate the root with any algorithm you like (any iterative approximation like bisection or Newton method could work).
Multiply the result.
If the exponent was negative, apply the inverse.
Example:
2^(-3.5) = (2^3 * 2^(1/2)))^-1 = 1 / (2*2*2 * sqrt(2))
|
2,882,721 | 2,882,745 | how to Clean up(destructor) a dynamic Array of pointers? | Is that Destructor is enough or do I have to iterate to delete the new nodes??
#include "stdafx.h"
#include<iostream>
using namespace std;
struct node{
int row;
int col;
int value;
node* next_in_row;
node* next_in_col;
};
class MultiLinkedListSparseArray {
private:
char *logfile;
node** rowPtr;
node** colPtr; // used in constructor
node* find_node(node* out);
node* ins_node(node* ins,int col);
node* in_node(node* ins,node* z);
node* get(node* in,int row,int col);
bool exist(node* so,int row,int col);
//add anything you need
public:
MultiLinkedListSparseArray(int rows, int cols);
~MultiLinkedListSparseArray();
void setCell(int row, int col, int value);
int getCell(int row, int col);
void display();
void log(char *s);
void dump();
};
MultiLinkedListSparseArray::MultiLinkedListSparseArray(int rows,int cols){
rowPtr=new node* [rows+1];
colPtr=new node* [cols+1];
for(int n=0;n<=rows;n++)
rowPtr[n]=NULL;
for(int i=0;i<=cols;i++)
colPtr[i]=NULL;
}
MultiLinkedListSparseArray::~MultiLinkedListSparseArray(){ // is that destructor enough??
cout<<"array is deleted"<<endl;
delete [] rowPtr;
delete [] colPtr;
}
| If you inserted object pointers on those arrays(initially you are initializing them to NULL), you need to iterate them to delete each single object.
As always, one delete for each new.
|
2,882,763 | 2,882,813 | C++ .NET DLL vs C# Managed Code ? (File Encrypting AES-128+XTS) | I need to create a Windows Mobile Application (WinMo 6.x - C#) which is used to encrypt/decrypt files. However it is my duty to write the encryption algorithm which is AES-128 along with XTS as the mode of operation. RijndaelManaged just doesn't cut it :( Very much slower than DES and 3DES CryptoServiceProviders :O
I know it all depends on how good I am at writing the algorithm in the most efficient way. (And yes I my self have to write it from scratch but i can take a look @ other implementations)
Nevertheless, does writing a C++ .NET DLL to create the encryption/decryption algorithm + all the file handling and using it from C# have a significant performance advantage OVER writing the encryption algorithm + file handling in completely managed C# code?
If I use C++ .NET to create the encryption algorithm, should I use MFC Smart Device DLL or ATL? What is the difference and is there any impact on which one I choose? And can i just add a reference to the C++ DLL from C# or should I use P/Invoke?
I am fairly competent with C# than C++ but performance plays a major role as I have convinced my lecturers that AES is a very efficient cryptographic algorithm for resource constrained devices.
Thanx a bunch :)
| Writing a "managed" program will have equal performance in C++ or C# or VB, since they all compile to IL anyway.
I don't know, but if you write an unmanaged C++ class library and invoke it from managed C# app you may loose some performance during the p/invoke but your speed increase (from going unmanaged) may be enough to justify it. There's an equal chance the p/invoke might cancel it out any potential performance gain from going unmanaged.
I don't think there's anyway to know for sure without doing it both ways and testing.
|
2,882,957 | 2,883,026 | Dynamic stack allocation in C++ | I want to allocate memory on the stack.
Heard of _alloca / alloca and I understand that these are compiler-specific stuff, which I don't like.
So, I came-up with my own solution (which might have it's own flaws) and I want you to review/improve it so for once and for all we'll have this code working:
/*#define allocate_on_stack(pointer, size) \
__asm \
{ \
mov [pointer], esp; \
sub esp, [size]; \
}*/
/*#define deallocate_from_stack(size) \
__asm \
{ \
add esp, [size]; \
}*/
void test()
{
int buff_size = 4 * 2;
char *buff = 0;
__asm
{ // allocate
mov [buff], esp;
sub esp, [buff_size];
}
// playing with the stack-allocated memory
for(int i = 0; i < buff_size; i++)
buff[i] = 0x11;
__asm
{ // deallocate
add esp, [buff_size];
}
}
void main()
{
__asm int 3h;
test();
}
Compiled with VC9.
What flaws do you see in it?
Me for example, not sure that subtracting from ESP is the solution for "any kind of CPU".
Also, I'd like to make the commented-out macros work but for some reason I can't.
| Sorry, but you'd be better off using alloca than doing that kind of stuff. Not only it's x86 specific, but also, it'll probably give unexpected results if compiled with optimizations on.
alloca is supported by many compilers, so you shouldn't be running into problems anytime soon.
|
2,883,164 | 2,895,561 | OpenSSL certificate lacks key identifiers | How do i add these sections to certificate (i am manualy building it using C++).
X509v3 Subject Key Identifier:
A4:F7:38:55:8D:35:1E:1D:4D:66:55:54:A5:BE:80:25:4A:F0:68:D0
X509v3 Authority Key Identifier:
keyid:A4:F7:38:55:8D:35:1E:1D:4D:66:55:54:A5:BE:80:25:4A:F0:68:D0
Curently my code builds sertificate well, except for those keys.. :/
static X509 * GenerateSigningCertificate(EVP_PKEY* pKey)
{
X509 *x;
x = X509_new(); //create x509 certificate
X509_set_version(x, NID_X509);
ASN1_INTEGER_set(X509_get_serialNumber(x), 0x00000000); //set serial number
X509_gmtime_adj(X509_get_notBefore(x), 0);
X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*365); //1 year
X509_set_pubkey(x, pKey); //set pub key from just generated rsa
X509_NAME *name;
name = X509_get_subject_name(x);
NAME_StringField(name, "C", "LV");
NAME_StringField(name, "CN", "Point"); //common name
NAME_StringField(name, "O", "Point"); //organization
X509_set_subject_name(x, name); //save name fields to certificate
X509_set_issuer_name(x, name); //save name fields to certificate
X509_EXTENSION *ex;
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_cert_type, "server");
X509_add_ext(x,ex,-1);
X509_EXTENSION_free(ex);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_comment, "example comment extension");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_ssl_server_name, "www.lol.lv");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_basic_constraints, "critical,CA:TRUE");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
X509_sign(x, pKey, EVP_sha1()); //sign x509 certificate
return x;
}
| Found solution - add these lines to code
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_key_identifier, "hash");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
ex = X509V3_EXT_conf_nid(NULL, NULL, NID_authority_key_identifier, "keyid:always");
X509_add_ext(x, ex, -1);
X509_EXTENSION_free(ex);
|
2,883,353 | 2,883,458 | Constant embedded for loop condition optimization in C++ with gcc | Will a compiler optimize tihs:
bool someCondition = someVeryTimeConsumingTask(/* ... */);
for (int i=0; i<HUGE_INNER_LOOP; ++i)
{
if (someCondition)
doCondition(i);
else
bacon(i);
}
into:
bool someCondition = someVeryTimeConsumingTask(/* ... */);
if (someCondition)
for (int i=0; i<HUGE_INNER_LOOP; ++i)
doCondition(i);
else
for (int i=0; i<HUGE_INNER_LOOP; ++i)
bacon(i);
someCondition is trivially constant within the for loop.
This may seem obvious and that I should do this myself, but if you have more than one condition then you are dealing with permuatations of for loops, so the code would get quite a bit longer. I am deciding on whether to do it (I am already optimizing) or whether it will be a waste of my time.
| It's possible that the compiler might write the code as you did, but I've never seen such optimization.
However there is something called branch prediction in modern CPU. In essence it means that when the processor is asked to execute a conditional jump, it'll start to execute what is judged to be the likeliest branch before evaluating the condition. This is done to keep the pipeline full of instructions.
In case the processor fails (and takes the bad branch) it cause a flush of the pipeline: it's called a misprediction.
A very common trait of this feature is that if the same test produce the same result several times in a row, then it'll be considered to produce the same result by the branch prediction algorithm... which is of course tailored for loops :)
It makes me smile because you are worrying about the if within the for body while the for itself causes a branch prediction >> the condition must be evaluated at each iteration to check whether or not to continue ;)
So, don't worry about it, it costs less than a cache miss.
Now, if you really are worried about this, there is always the functor approach.
typedef void (*functor_t)(int);
functor_t func = 0;
if (someCondition) func = &doCondition;
else func = &bacon;
for (int i=0; i<HUGE_INNER_LOOP; ++i) (*func)(i);
which sure looks much better, doesn't it ? The obvious drawback is the necessity for compatible signatures, but you can write wrappers around the functions for that. As long as you don't need to break/return, you'll be fine with this. Otherwise you would need a if in the loop body :D
|
2,883,810 | 2,883,977 | What effect does static const have on a namespace member | // MyClass.h
namespace MyNamespace {
static const double GasConstant = 1.987;
class MyClass
{
// constructors, methods, etc.
};
}
I previously had GasConstant declared within the MyClass declaration (and had a separate definition in the source file since C++ does not support const initialization of non-integral types). I however need to access it from other files and also logically it seems like it should reside at the namespace level.
My questions is, what effect does static const have in this case? Clearly const means I can't assign a new value to GasConstant, but what does a static member at the namespace mean. Is this similar to static at file scope, where the member is not accessible outside of the unit?
| The use of static at namespace scope is was* deprecated in C++. It would normally only ever be seen in a source file, where its effect is to make the variable local to that source file. That is, another source file can have a variable of exactly the same name with no conflict.
In C++, the recommended way to make variables local to the source file is to use an anonymous namespace.
I think it's fair to say the static in the header in your code is simply incorrect.
*As pointed out by Tom in the comments (and in this answer), the C++ committee reversed the decision to deprecate static use at file scope, on the basis that this usage will always be part of the language (e.g. for C compatibility).
|
2,883,829 | 2,884,710 | Template compiling errors on iPhone SDK 3.2 | I'm porting over some templated code from Windows and I'm hitting some compiler differences on the iPhone 3.2 SDK.
Original code inside a class template's member function is:
return BinarySearch<uint32, CSimpleKey<T> >(key);
where BinarySearch is a method inherited from another template.
This produces the following error:
csimplekeytable.h:131: error: no matching function for call to 'BinarySearch(NEngine::uint32&)'
The visual studio compiler seems to walk up the template hierarchy fine but gcc needs me to fully qualify where the function comes from (I have verified this by fixing the same issues with template member variables that way).
So I now need to change this into:
return CSimpleTable<CSimpleKey<T> >::BinarySearch<uint32, CSimpleKey<T> >(key);
Which now produces the following error:
csimplekeytable.h:132: error: expected primary-expression before ',' token
csimplekeytable.h:132: error: expected primary-expression before '>' token
After some head scratching, I believe what's going on here is that it's trying to resolve the '<' before BinarySearch as a 'Less Than' operator for some reason.
So two questions:
- Am I on the right path with my interpretation of the error?
- How do I fix it?
-D
| If CSimpleTable is the base class, you need to qualify your call with that base class name or alternatively with this. But since both of these depend on the template parameters, the compiler cannot lookup what the name BinarySearch means. It could be a static integer constant, which you compare against something else, or it could be a template that you put arguments enclosed in <...> for. You need to tell the compiler about the latter
/* the "::template" means: 'the name that follows is a template' */
return CSimpleTable<CSimpleKey<T> >::template BinarySearch<uint32, CSimpleKey<T> >(key);
Or with this
return this->template BinarySearch<uint32, CSimpleKey<T> >(key);
The reason for the qualification is that the compiler does not look for unqualified names in base classes that depend on template parameters (in your case the parameter is T), since the binding of the name would depend on whether the base class has such a name or not, which is considered unfortunate. For a plain name like BinarySearch, there is in addition no indication that this name depends on a template parameter, thus the Standard requires compilers not to delay lookup of the name until instantiation. So the name, even if lookup in dependent bases would be allowed on instantiation (which isn't), couldn't be found anyway.
You have to explicitly tell the compiler to look in the enclosing class by qualifying it, in which event the compiler will include dependent base classes during lookup when instantiating. Prefixing with this or the class name will also make the name dependent, thus delaying lookup of it until instantiation. These two facts are required for it to work.
|
2,883,841 | 2,886,943 | embedded dev. question - how to break free from a faulty serial port opening? | Under WindowsCE, C++ project, I'm trying to work with devices connected via both "real" serial ports and/or serial-to-usb wrappers ("virtual" serial ports); my problem is - when I try to open the port, if something goes wrong, the function never returns and the system goes into some non-responsive state and has to be eventually rebooted. I need to open the ports from the main thread. The question is - how can I make it happen in a controlled way??
this is the opening code snippet:
std::ostringstream device_name;
device_name << "\\\\.\\COM" << port;
m_port = ::CreateFile(device_name.str().c_str(),
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, // overlapped I/O
NULL); // null template
any suggestions would be greatly appreciated
thanks!
| Why not perform the open in another thread? There's no reason to do anything else in that thread - just open the port and you can use the handle for the opened port in any other thread in your process.
However, I'm not sure what's so screwed up that your CreateFile() call seems to hang - I wonder if this happens even on another thread whether things will still be stable in your application.
|
2,884,097 | 2,884,140 | Optimal (Time paradigm) solution to check variable within boundary | Sorry if the question is very naive.
I will have to check the below condition in my code
0 < x < y
i.e code similar to if(x > 0 && x < y)
The basic problem at system level is - currently, for every call (Telecom domain terminology), my existing code is hit (many times). So performance is very very critical, Now, I need to add a check for boundary checking (at many location - but different boundary comparison at each location).
At very normal level of coding, the above comparison would look very naive without any issue. However, when added over my statistics module (which is dipped many times), performance will go down.
So I would like to know the best possible way to handle the above scenario (kind of optimal way for limits checking technique). Like for example, if bit comparison works better than normal comparison or can both the comparison be evaluation in shorter time span?
Other Info
x is unsigned integer (which must be checked to be greater than 0 and less than y).
y is unsigned integer.
y is a non-const and varies for every comparison.
Here time is the constraint compared to space.
Language - C++.
Now, later if I need to change the attribute of y to a float/double, would there be another way to optimize the check (i.e will the suggested optimal technique for integer become non-optimal solution when y is changed to float/double).
Thanks in advance for any input.
PS : OS used is SUSE 10 64 bit x64_64, AIX 5.3 64 bit, HP UX 11.1 A 64.
| As always, profile first, optimize later. But, given that this is actually an issue, these could be things to look into:
"Unsigned and greater than zero" is the same as "not equal to zero", which is usually about as fast as a comparison gets. So a first optimization would be to do x != 0 && x < y.
Make sure that you do the comparison that is most likely to fail the first one, to maximize the gain from short circuiting.
If possible, use compiler directives to tell the compiler about the most likely code path. This will optimize instruction prefetching etc. I.e. for GCC look at something like this, done in the kernel.
I don't think tricks with subtraction and comparison against zero, etc. will be of any gain. If that is the most effective way to do a less-than comparison, you can be sure your compiler already knows about it.
|
2,884,170 | 2,884,211 | cast operator to base class within a thin wrapper derived class | I have a derived class that's a very thin wrapper around a base class. Basically, I have a class that has two ways that it can be compared depending on how you interpret it so I created a new class that derives from the base class and only has new constructors (that just delegate to the base class) and a new operator==. What I'd like to do is overload the operator Base&() in the Derived class so in cases where I need to interpret it as the Base.
For example:
class Base
{
Base(stuff);
Base(const Base& that);
bool operator==(Base& rhs); //typical equality test
};
class Derived : public Base
{
Derived(stuff) : Base(stuff) {};
Derived(const Base& that) : Base(that) {};
Derived(const Derived& that) : Base(that) {};
bool operator==(Derived& rhs); //special case equality test
operator Base&()
{
return (Base&)*this; //Is this OK? It seems wrong to me.
}
};
If you want a simple example of what I'm trying to do, pretend I had a String class and String==String is the typical character by character comparison. But I created a new class CaseInsensitiveString that did a case insensitive compare on CaseInsensitiveString==CaseInsensitiveString but in all other cases just behaved like a String. it doesn't even have any new data members, just an overloaded operator==. (Please, don't tell me to use std::string, this is just an example!)
Am I going about this right? Something seems fishy, but I can't put my finger on it.
| Since your Derived is derived from Base publically, your Derived is already convertible to Base &. There's no need to implement anything extra.
Moreover, when it comes to conversion operator itself, whether you are doing it right or wrong is a moot question, since your conversion operator will never be used anyway. The derived-to-base conversion is always handled by the built-in means. If you provide your own operator for the conversion (as you do above) it will be ignored anyway.
I don't get though how you were planning to use if to solve the original problem with different comparison approaches.
|
2,884,172 | 2,884,242 | Algorithm for dividing very large numbers | I need to write an algorithm(I cannot use any 3rd party library, because this is an assignment) to divide(integer division, floating parts are not important) very large numbers like 100 - 1000 digits. I found http://en.wikipedia.org/wiki/Fourier_division algorithm but I don't know if it's the right way to go. Do you have any suggestions?
1) check divisior < dividend, otherwise it's zero (because it will be an int division)
2) start from the left
3) get equal portion of digits from the dividend
4) if it's divisor portion is still bigger, increment digits of dividend portion by 1
5) multiply divisor by 1-9 through the loop
6) when it exceeds the dividend portion, previous multiplier is the answer
7) repeat steps 3 to 5 until reaching to the end
| Knuth, Donald, The Art of Computer Programming, ISBN 0-201-89684-2, Volume 2: Seminumerical Algorithms, Section 4.3.1: The Classical Algorithms
|
2,884,361 | 2,884,371 | How to templatize the container type in a function declaration? | I want to write a function that accepts any container holding strings. Something like this:
template <typename Container> void foo(Container<string>& stuff);
But this isn't the right syntax. What's the right syntax?
| You need a template template parameter:
template < template <typename> class Container> void foo (Container<string>& stuff);
|
2,884,797 | 2,885,843 | SWIG: Throwing exceptions from Python to C++ | We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on SO.
It's fairly straight forward and I'm not expecting issues with handling our library's own exceptions. What I'd like to know and can't seem to find in the documentation is how to have our Python implementation of the extended C++ interface throw those C++ exceptions in a way that makes them visible to the C++ code.
We could make small functions within the *.i files such that each function throws our exceptions:
void throw_myException(){ throw MyException; }
but I'm wondering how it will interact with the Python code.
Anyone have any experience with throwing C++ exceptions from Python code?
| (C)Python is written in C. It seems that it could be bad to throw exceptions "through" the interpreter.
My feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.
That's basically what we do here, although we're using C# instead of Python to generate the "error code" data which then gets translated to the C++ layer and then sent off to the exception factory.
|
2,884,814 | 2,884,907 | Is using a C++ "Virtual Constructor" generally considered good practice? | Yes i know the phrase "virtual constructor" makes no sense but i still see articles like this
one: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=184
and i'v heard it mentioned as a c++ interview.
What is the general consensus?
Is a "Virtual Constructor" good practice or something to be avoided completely?
To be more more precise, can some one provide me with a real world scenario where they have had to use it, from where i stand this concept of virt. constr. is a somewhat useless invention but i could be wrong.
| All the author has done is implement prototyping and cloning. Both of which are powerful tools in the arsenal of patterns.
You can actually do something a lot closer to "virtual constructors" through the use of the handle/body idiom:
struct object
{
void f();
// other NVI functions...
object(...?);
object(object const&)
object& operator = (object const&);
~object();
private:
struct impl;
impl * pimpl;
};
struct object::impl
{
virtual void f() = 0;
virtual impl* clone() = 0;
// etc...
};
struct impA : object::impl { ... };
struct impB : object::impl { ... };
object::object(...?) : pimpl(select_impl(...?)) {}
object::object(object const& other) : pimpl(other.pimpl->clone()) {}
// etc...
Don't know if anyone has declared this an Idiom but I've found it useful and I'm sure others have come across the same idea themselves.
Edit:
You use factory methods or classes when you need to request an implementation for an interface and do not want do couple your call sites to the inheritance tree behind your abstraction.
You use prototyping (clone()) to provide generic copying of an abstraction so that you do not have to determine type in order to make that copy.
You would use something like I just showed for a few different reasons:
1) You wish to totally encapsulate the inheritance relation behind an abstraction. This is one method of doing so.
2) You want to treat it as a value type at the abstract level (you'd be forced to use pointers or something otherwise)
3) You initially had one implementation and want to add new specifications without having to change client code, which is all using the original name either in an auto declaration or heap allocation by name.
|
2,885,117 | 2,885,140 | How do you stop in TotalView after an MPI Error? | I am using TotalView and am getting an MPI_Error. However, Totalview does not stop on this error and I can't find where it is occurring. I believe this also applies to GDB.
| Define an MPI_ErrHandler. It gets called in place of the default MPI handler and you can set a breakpoint there. Suggestions welcome on how to get it to print the same thing as the MPI error, or better yet, more information.
MPIErrorHander.hpp:
#define MPIERRORHANDLER_HPP
#ifdef mpi
#include <stdexcept>
#include <string>
#include <mpi.h>
namespace MPIErrorHandler {
//subclass so we can specifically catch MPI errors
class Exception : public std::exception {
public:
Exception(std::string const& what) : std::exception(), m_what(what) { }
virtual ~Exception() throw() { }
virtual const char* what() const throw() {
return m_what.c_str( );
}
protected:
std::string m_what;
};
void convertToException( MPI_Comm *comm, int *err, ... );
}
#endif // mpi
#endif // MPIERRORHANDLER_HPP
MPIErrorHandler.cpp:
#ifdef mpi
#include "MPIErrorHandler.hpp"
void MPIErrorHandler::convertToException( MPI_Comm *comm, int *err, ... ) {
throw Exception(std::string("MPI Error."));
}
#endif //mpi
main.cpp:
#include "MPIErrorHandler.hpp"
{
MPI_Errhandler mpiErrorHandler;
MPI_Init( &argc, &argv );
//Set this up so we always get an exception that will stop TV
MPI_Errhandler_create( MPIErrorHandler::convertToException,
&mpiErrorHandler );
MPI_Errhandler_set( MPI_COMM_WORLD, mpiErrorHandler );
// Your program here.
MPI_Finalize( );
}
|
2,885,121 | 2,885,155 | How to create a step by step wizard in C++ (with unmanaged code) in Visual Studio 2010 | I would like to build a small wizard in C++ with no dependencies on any framework.
Apparently, is really simple, but I don't know where to start. Can you point me to good information (tutorials, etc) on it. Should I use MFC Application or a Win32 project? Is there any step by step guide ?
I'm using VS 2010. The majority of info I'd found on MFC is really old. It seems like the vast majority of development is going .net.
| Look up Property Sheets in MFC http://msdn.microsoft.com/en-us/library/cfs4wk4e%28VS.80%29.aspx
|
2,885,132 | 2,885,201 | Multi-argument template functions, overloading and ambiguity errors | Lets say I'm writing a some kind of conversion operator, and I want to use it like that:
SomeType a;
AnotherType b = conv<AnotherType>(a);
First, I write the base (default) function:
template <typename T, typename U>
inline T conv(const U& a)
{
return T(a);
}
Full specialization (or a non-template overload) is not a problem, however, when I want to do something like that:
template <typename T>
inline Point<T> conv(const Ipoint& p)
{
return Point<T>(p.x, p.y);
}
I can't write any more conversion functions from the Ipoint (to the FunkyPoint< T > for example) due to ambiguity, and I end up with an awkward usage:
Ipoint a;
Point<double> b = conv<double>(a); //ugly!
//Point<double> b = conv<Point<double> >(a); //I want that, but it (obviously) does not compile.
Is there any way of doing it nicely?
| Implement the body in a class template and then you can partially specialize:
template < typename T, typename U >
struct convert
{
static T apply(U const& u) { return T(u); }
};
template < typename T, typename U >
T conv(U const& u) { return convert<T,U>::apply(u); }
template < typename T >
struct convert<Point<T>, Ipoint>
{
static Point apply(Ipoint const& u)
{
return Point(u.x, u.y);
}
};
Should work but is untested.
|
2,885,244 | 2,885,258 | C++ How do I give a member variable in an abstract class a default value? | In the header, I'm defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding
AbstractClass::isActive = false;
to the cpp file, but that causes the error "Expected constructor, destructor, or type conversion before '=' token."
| Initialize it in the class' constructor:
class AbstractClass {
bool isActive;
AbstractClass() : isActive(false) {
}
// ...
};
That the class contains abstract methods doesn't stop it from having a constructor that is used to initialize its member variables.
|
2,885,302 | 2,885,345 | Getting a type for a template instantiation? | I have the following situation:
I have a object of type MyClass, which has a method to cast itself to its base class. The class includes a typedef for its base class and a method to do the upcast.
template <class T, class B>
class BaseClass;
template <class T>
class NoAccess;
template <class T>
class MyClass : public BaseClass<T, NoAccess<T> >
{
private:
typedef BaseClass<T, NoAccess<T> > base;
public:
base &to_base();
};
I need to pass the result of a base call to a functor Operator:
template <class Y>
class Operator
{
Operator(Y &x);
};
Operator<???> op(myobject.to_base());
Is there a easy way to fill the ??? provided that I do not want to use NoAccess?
| You can define a factory function to use type deduction:
template< class Y >
Operator<Y> create_operator( Y &y ) {
return Operator<Y>( y );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.