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
|
|---|---|---|---|---|
466,568
| 466,592
|
(C++) Need to figure out all points within a radius using reg. 2D windows coord. system
|
Sorry in advance, I'm struggling a bit with how to explain this... :)
Essentially, I've got a typical windows coordinate system (the Top, Left is 0,0). If anybody's familiar with the haversine query, like in SQL, it can get all points in a radius based on latitude and longitude coordinates.
I need something much simpler, but my math skills ain't all up to par! Basically, I've got random points scattered throughout about a 600x400 space. I have a need to, for any X,Y point on the map, run a query to determine how many other points are within a given radius of that one.
If that's not descriptive enough, just let me know!
|
Use Pythagoras:
distance = sqrt(xDifference^2 + yDifference^2)
Note that '^' in this example means "to the power of" and not C's bitwise XOR operator. In other words the idea is to square both differences.
|
466,802
| 467,363
|
How do I parse this correctly with spirit?
|
My situation: I'm new to Spirit, I have to use VC6 and am thus using Spirit 1.6.4.
I have a line that looks like this:
//The Description;DESCRIPTION;;
I want to put the text DESCRIPTION in a string if the line starts with //The Description;.
I have something that works but looks not that elegant to me:
vector<char> vDescription; // std::string doesn't work due to missing ::clear() in VC6's STL implementation
if(parse(chars,
// Begin grammar
(
as_lower_d["//the description;"]
>> (+~ch_p(';'))[assign(vDescription)]
),
// End grammar
space_p).hit)
{
const string desc(vDescription.begin(), vDescription.end());
}
I would much more like to assign all printable characters up to the next ';' but the following won't work because parse(...).hit == false
parse(chars,
// Begin grammar
(
as_lower_d["//the description;"]
>> (+print_p)[assign(vDescription)]
>> ';'
),
// End grammar
space_p).hit)
How do I make it hit?
|
You might try using confix_p:
confix_p(as_lower_d["//the description;"],
(+print_p)[assign(vDescription)],
ch_p(';')
)
It should be equivalent to Fred's response.
The reason your code fails is because print_p is greedy. The +print_p parser will consume characters until it encounters the end of the input or a non-printable character. Semicolon is printable, so print_p claims it. Your input gets exhausted, the variable is assigned, and the match fails — there's nothing left for the last semicolon of your parser to match.
Fred's answer constructs a new parser, (print_p - ';'), which matches everything print_p does, except for semicolons. "Match everything except X, and then match X" is a common pattern, so confix_p is provided as a shortcut for constructing that kind of parser. The documentation suggests using it for parsing C- or Pascal-style comments, but that's not required.
For your code to work, Spirit would need to recognize that the greedy print_p matched too much and then backtrack to allow matching less. But although Spirit will backtrack, it won't backtrack to the "middle" of what a sub-parser would otherwise greedily match. It will backtrack to the next "choice point," but your grammar doesn't have any. See Exhaustive backtracking and greedy RD in the Spirit documentation.
|
466,820
| 466,842
|
Math Resources for C/C++ Programmers
|
My degree is in Electrical and Computer Engineering but i'm currently employed as a Software Engineer. I took all of the algebra, geometry and calculus classes that one would expect from someone with my degree however I must admit, I think I learned just enough to pass the test but never really saw a use for it and therefore never really retained much of the material.
Now that i've matured some, I see the use for it all of the time. I KNOW that there are lots of places that math knowledge would improve my coding so i'm ready to relearn the old stuff and learn some new stuff.
What are your favorite resources out there? (Resources that can tie math into programming are even better if you have any!) Books? Websites? Blogs?
|
I found this blog on the subject intresting:
http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html
also has some recommendations for books.
|
466,827
| 466,866
|
Warnings and SunStudio C++ compiler
|
I talked my team into turning on compiler warnings again. Some how all warnings (-w) were disabled (don't ask...). Most of them are obvious but one of them is really annoying. I get it from my date and time classes which are used in lots of places. Story is really simple. Time is subclass of Date and both of them have their operators defined. What can be wrong with that? Here's the warning I get:
Warning: ACTime::operator- hides the function ACDate::operator-(const ACDate&) const.
Perhaps somebody can link me the docs describing what each of SunStudio C++ compiler warnings mean? I can't find this... Thanks!
|
I can help you with that particular warning - it looks a lot like this one from C++ FAQ Lite. Did you by chance change the type of argument that ACTime::operator- uses from the one in ACDate?
|
467,139
| 467,177
|
Portable wchar_t in C++
|
Is there a portable wchar_t in C++? On Windows, its 2 bytes. On everything else is 4 bytes. I would like to use wstring in my application, but this will cause problems if I decide down the line to port it.
|
If you're dealing with use internal to the program, don't worry about it; a wchar_t in class A is the same as in class B.
If you're planning to transfer data between Windows and Linux/MacOSX versions, you've got more than wchar_t to worry about, and you need to come up with means to handle all the details.
You could define a type that you'll define to be four bytes everywhere, and implement your own strings, etc. (since most text handling in C++ is templated), but I don't know how well that would work for your needs.
Something like typedef int my_char; typedef std::basic_string<my_char> my_string;
|
467,150
| 665,635
|
What are some good C++ resources for effectively using Apache XML Security?
|
I'm looking for some resources that allow me to understand how to use this library, particularly for signing XML. Most of what I found out there is Java related, and I would prefer to get documentation/FAQs/tutorials on the C++ library.
|
I had the same problem. The best information I could find was on the Apache website itself ( http://santuario.apache.org/c/programming.html ), the API docs and by looking at the code of the examples and tools (like templatesign) they provide.
This information combined with some experimenting was enough for me to sign and verify XML documents. Basically I just used templatesign and checksig as starting point.
The most problems I had was with C14N, so if there is something not working try dumping the raw data streams which Apache is using internally and check if it really signs/verifies what you expect.
|
467,300
| 474,157
|
How to use msxml with Visual Studio 2008 Express (no ATL classes) without becoming crazy?
|
It is not really a question because I have already found a solution. It took me a lot of time, that's why I want to explain it here.
Msxml is based on COM so it is not really easy to use in C++ even when you have helpful classes to deal with memory allocation issues. But writing a new XML parser would be much more difficult so I wanted to use msxml.
The problem:
I was able to find enough examples on the internet to use msxml with the help of CComPtr (smart pointer to avoid having to call Release() for each IXMLDOMNode manually), CComBSTR (to convert C++ strings to the COM format for strings) and CComVariant. This 3 helpful classes are ATL classes and need an #include <atlbase.h>.
Problem: Visual Studio 2008 Express (the free version) doesn't include ATL.
Solution:
Use comutil.h and comdef.h, which include some simple helper classes:
_bstr_t replaces more or less CComBSTR
_variant_t replaces more or less CComVariant
_com_ptr_t replaces indirectly CComPtr through the use of _COM_SMARTPTR_TYPEDEF
Small example:
#include <msxml.h>
#include <comdef.h>
#include <comutil.h>
// Define some smart pointers for MSXML
_COM_SMARTPTR_TYPEDEF(IXMLDOMDocument, __uuidof(IXMLDOMDocument)); // IXMLDOMDocumentPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMElement, __uuidof(IXMLDOMElement)); // IXMLDOMElementPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNodeList, __uuidof(IXMLDOMNodeList)); // IXMLDOMNodeListPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNamedNodeMap, __uuidof(IXMLDOMNamedNodeMap)); // IXMLDOMNamedNodeMapPtr
_COM_SMARTPTR_TYPEDEF(IXMLDOMNode, __uuidof(IXMLDOMNode)); // IXMLDOMNodePtr
void test_msxml()
{
// This program will use COM
CoInitializeEx(NULL, COINIT_MULTITHREADED);
{
// Create parser
IXMLDOMDocumentPtr pXMLDoc;
HRESULT hr = CoCreateInstance(__uuidof (DOMDocument), NULL, CLSCTX_INPROC_SERVER, IID_IXMLDOMDocument, (void**)&pXMLDoc);
pXMLDoc->put_validateOnParse(VARIANT_FALSE);
pXMLDoc->put_resolveExternals(VARIANT_FALSE);
pXMLDoc->put_preserveWhiteSpace(VARIANT_FALSE);
// Open file
VARIANT_BOOL bLoadOk;
std::wstring sfilename = L"testfile.xml";
hr = pXMLDoc->load(_variant_t(sfilename.c_str()), &bLoadOk);
// Search for node <testtag>
IXMLDOMNodePtr pNode;
hr = pXMLDoc->selectSingleNode(_bstr_t(L"testtag"), &pNode);
// Read something
_bstr_t bstrText;
hr = pNode->get_text(bstrText.GetAddress());
std::string sSomething = bstrText;
}
// I'm finished with COM
// (Don't call before all IXMLDOMNodePtr are out of scope)
CoUninitialize();
}
|
I'm happy I posted my question although I already had a solution because I got several alternative solutions. Thanks for all your answers.
Using another parser such as eXpat or the maybe smaller (not so powerfull but enough for my needs) TinyXML could actually be a good idea (and make it easier to port the program to another operating system).
Using an #import directive, apparently a Microsoft specific extension to simplify the use of COM, is also interesting and brought me to the following web page MSXML in C++ but as elegant as in C#, which explain how to simplify the use of msxml as much as possible.
|
467,327
| 467,376
|
Upgrading to SQL Server 2005: Cannot INSERT QNAN into float column?
|
Background:
I'm working on migrating from SQL Server 2000 to SQL Server 2005. This is providing DB service for a C++ application that uses SQL Native Client to communicate with SQL Server via ODBC.
Problem:
I'm attempting to insert QNAN into a float column in the database. In my application, this value is stored as a double (value: 1.#QNAN00000000000) and is sent into the database as a parameter. This was not a problem in SQL Server 2000 but the same code gives me the following error in SQL Server 20005:
The incoming tabular data stream (TDS)
remote procedure call (RPC) protocol
stream is incorrect. Parameter 3 (""):
The supplied value is not a valid
instance of data type float. Check the
source data for invalid values. An
example of an invalid value is data of
numeric type with scale greater than
precision.
Question:
Is it possible to get SQL Server 2005 to accept QNAN? If so, how?
|
According to the response to this bug report, SQL Server 2005 does not accept NaN or infinity, and this was apparently by design (due to sorting/comparison issues).
|
467,640
| 467,695
|
Compiler Error when adding dll reference to managed c++ project
|
I am using VS 2008 and get compiler errors sporadically when adding a dll reference to a managed c++ file in my C++ project. I am trying to add a reference to the dll so as to be able to use smart pointers.
ex: #import items.tlb
The problem is that the compiler crashes at sporadic places inside of items.tlh almost as though chunks of bytes where erased of missings , but when i open the file i can't find any reference to the aforementioned errors.
I tried to rebuild the whole project several times, tried on different machine, but although the compiler errors are not consistents and disappear alltogether sometimes , a fresh rebuild sometimes brings back the problem. I was told that the size of the generated .tlh file may be a reason but it doesn't really solve my problem or point me in the right direction.
Did anybody experienced the same symptoms?
Thank you
|
Whenever I've had this problem, it was caused by linking a Debug build to a Release DLL or a Release build to a Debug DLL.
|
467,762
| 467,804
|
Which language/platform to develop desktop application based on following criteria
|
Faced with the challenge of a new application with which you had free reign to design, assemble a team to develop and manage:
Which language/platform would you choose?
Why?
Background: The desktop application will control a hardware device and perform computations, analyze and display the data returned by it.
Requirements: (importance: 10=most important)
will need to communicate with devices using USB and/or ethernet (9)
availability of engineers with relevant skills (8)
availability of quality IDE/tools (8)
cost of IDE/tools (7)
availability of resources, tutorials, support (9)
lifetime of language/API/platform/framework- ie how future-proof will the investment in this application be?... the product has a long life-cycle (10)
cross-platform (3)
richness and breadth of libraries available (9)
the application will need to be able to interpret a scripting language (6)
unit testing (9)
Assumptions:
For USB variants of the device, a device driver will be written in C/C++
Application will be a completely new endeavor - from scratch
Background of existing engineers is C/C++, and they have a strong OO competence. Existing engineers are willing to adopt best language/platform, and new engineers with appropriate skills will be recruited.
Shortlist (which you can add to):
Java/J2SE
C#/.NET
C++/wxWidgets
C++/QT
etc.
Looking forward to hearing what you think!
|
To be honest, I'd choose Java (with a small component of C) for the following reasons, based on your requirements.
Lifetime of language/API/platform/framework- i.e., how future-proof will the investment in this application be?... the product has a long life-cycle (10). That really depends on what you mean by long. I seriously can't imagine Java disappearing, simply due to its huge installed base. C or C++ isn't disappearing either but I always think of the VB6-to-VB.net migration issues when contemplating the future of C#.
Will need to communicate with devices using USB and/or ethernet (9). Whilst Java isn't directly ideal for this, it has JNI to do the grunt work. You'll still need a C component to do this (and it will change for each platform but it's better to have the bulk of your code write-once - with C, you'll probably have most of your code changing for each platform, and with C#, well, is it really supported on platforms other than Windows?). Another alternative is JNA which looks like a "Python ctypes" for Java (access to shared libraries and DLLs without the JNI interfacing layer).
Availability of resources, tutorials, support (9). All the languages have a huge resource cross-section on the web.
Richness and breadth of libraries available (9). You have Boost for C++ and cross-platform GUIs but they're something that has to be added - there's nothing built in to the development environment like with Eclipse/Java.
Unit testing (9). Same response as availability of tools below - there are plenty of (free) Eclipse plug-ins that automate unit testing.
Availability of engineers with relevant skills (8). All the languages you mention have a plethora (I love using that word) of people able to do the job.
Availability of quality IDE/tools (8). This is Eclipse. No two ways about it, in my mind. The number of plug-ins for it is truly immense. NetBeans may look nicer but I'd rather have functionality than looks (and so would my wife, so that's lucky :-).
Cost of IDE/tools (7). Eclipse is free.
The application will need to be able to interpret a scripting language (6). Last I heard, Java now includes JavaScript as a built-in as well as the ability for developers to add their own scripting engines.
Cross-platform (3). C#, no (despite the existence of Mono, I still see risks that it will fall afoul of MS one day, and that not many is the FOSS world will work on it due to its MS associations).
|
467,815
| 467,830
|
Class method and variable with same name, compile error in C++ not in Java?
|
class Test {
bool isVal() const {
return isVal;
}
private:
bool isVal;
};
On Compiling this file it says
testClass.cpp:9: declaration of `bool
Test::isVal'
testClass.cpp:3: conflicts with
previous declaration `bool
Test::isVal()'
Although the same would work for java
class Test {
private boolean isVal;
public boolean isVal() {
return isVal;
}
}
Why does the compile error occur in C++ not in Java?
|
Because C++ is not Java. You can take the address of a member:
&Test::isVal
So you can't have two members have the same name, except that you can overload member functions. Even if you could disambiguate that by some kind of cast, the next problem would already arise at other places.
In C++, a lot of people including me usually call data members specially, like putting a m before their name. This avoids the problem:
class Test {
public:
bool IsVal() const { return mIsVal; }
private:
bool mIsVal;
};
|
467,851
| 467,853
|
Why can't we use "this" inside the class?
|
E,g
class Test {
public:
void setVal(const std::string& str) {
this.isVal = str; //This will error out
}
private:
string isVal;
};
|
In C++, this is a pointer (as opposed to a reference). So you have to say this->isVal instead.
|
468,090
| 468,430
|
How to restructure this code hierarchy (relating to the Law of Demeter)
|
I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body
class Body
from which I'll be deriving various implementations of a physics simulation. My game object class then looks like
class GameObject {
public:
// ...
private:
Body *m_pBody;
};
and I can plug in whatever implementation I need for that particular game. But I may need access to all of the Body functions when I've only got a GameObject. So I've found myself writing tons of things like
Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); }
I'm tempted to scratch all of them and just do stuff like
pObject->GetBody()->GetPosition();
but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.
|
The idea of the law of Demeter is that your GameObject isn't supposed to have functions like GetPosition(). Instead it's supposed to have MoveForward(int) or TurnLeft() functions that may call GetPosition() (along with other functions) internally. Essentially they translate one interface into another.
If your logic requires a GetPosition() function, then it makes sense turn that into an interface a la Ates Goral. Otherwise you'll need to rethink why you're grabbing so deeply into an object to call methods on its subobjects.
|
468,134
| 468,214
|
Newbie question about manual memory management and deep copying
|
Alright, so I'm trying out C++ for the first time, as it looks like I'll have to use it for an upcoming course in college. I have a couple years of programming under my belt, but not much in the non-garbage-collected world.
I have a class, a Node for use in a doubly linked list. So basically it has a value and two pointers to other Nodes. The main constructor looks like Node(const std::string & val, Node * prev, Node * next). The exercise includes a copy constructor that does a shallow copy of another Node, with a comment above it that says to change it to make a deep copy.
Here is what I thought that meant:
Node(const Node & other)
: value(other.value)
{
prev = new Node(other.prev->value, other.prev->prev, other.prev->next);
next = new Node(other.next->value, other.next->prev, other.next->next);
}
This seems to accomplish the goal of making it so that changing the copied Node doesn't affect the new Node. However, when I do it this way, I am allocating new stuff on the heap. This worries me, because I think it means that I should also be deleting it in the Node's destructor. But this is now inconsistent with the other constructor, where pointers to the Nodes are just passed in, already pointing to something. I can't rightly go deleteing next and prev in the destructor with that going on, right?
I'm really confused, guidance appreciated!
EDIT: Here is the code (before my above change to it), as requested:
#include <string>
//! Node implements a doubly-linked list node
class Node {
friend class LinkedList; //!< LinkedList can access private members of Node
public:
//! Constructor
Node(const std::string & v, Node * p, Node * n) :
value(v), prev(p), next(n)
{
}
//! Change to deep copy
Node(const Node & other) :
value(other.value), prev(other.prev), next(other.next)
{
}
//! Read-only public methods for use by clients of the LinkedList class
const std::string & GetValue() const
{
return value;
}
Node * GetPrevious()const
{
return prev;
}
Node * GetNext()const
{
return next;
}
//! Change to deep copy
Node & operator=(const Node & other)
{
if(this!=&other)
{
value=other.value;
prev=other.prev;
next=other.next;
}
return *this;
}
private:
std::string value; //!< value stored in the node
Node * prev; //!< pointer to previous node in the list
Node * next; //!< pointer to next node in the list
};
|
First of all, I'm not really sure how the objective of the exercise should be understood. How deep should the copy be? In a solution like yours, this->next->next and other.next->next would be still the same thing. Should this object also be duplicated? And the rest of the list? Where does it end? One could of course deep-copy the whole list, but this would be a quite unexpected behavior of a copy constructor of a single node, I think.
Is maybe the value member variable a pointer, that is supposed to be deep copied? That would make much more sense for me.
But back to your interpretation:
Node a(...);
// ... more code that adds a whole list to a
Node b(a);
There are two problems with your implementation. For one b->next->prev points to a, while I suspect it should point back to b. Secondly you need to think about the corner cases, where a might be the first or last node in the list.
And to your main question: you are of course right, somewhere the newly created objects need to be deleted again. No matter if you just copy the prev and next nodes or the whole list, I would say the user of that copy is responsible to delete all the copied nodes again. I assume with a normal, not-copied list, the user of that list would walk through all the nodes and delete them manually one after another, once he's done with the list. He wouldn't not assume the destructor of one node to delete the whole list. And the same goes for copies, they should behave the same. The user of the copied stuff should delete all the copies. (In practice you would probably have a list class, that does all that node management for you).
But again, if the copy constructor of the node copies the whole list, or even just several of it's nodes, this would be very unexpected and all the time people would forget to clean up all these copies. But that's not your node class' fault, but the exercise requirements'.
|
468,311
| 468,396
|
Using the "Very Sleepy" profiler to profile DLLs
|
I have a DLL that I want to profile.. I tried to use Very Sleepy, but I can't seem to get the source file column to display which source file the functions came from, all it displays is "unknown".. Anyway, I'm really baffled on how to use this app.. Can anyone point me to some help? There's not much documentation on it and it seems like it hasnt been maintained recently.. =/
Thanks..
EDIT: Adding another question:
What do the terms exclusive and inclusive mean in this app? Thanks..
|
You're going to need debugging information (PDB files) if you want to know the source file and column. That information doesn't get saved unless you ask for it.
Unfortunately the profiler has no documentation that I can find. However, there are definitions for inclusive and exclusive when it comes to profiling:
inclusive: total amount of time spent in function
exclusive: amount of time spent in function minus any time spent calling other functions
|
468,388
| 468,392
|
"Inherit not, contain" or "inherit, not contain"
|
I have an application which spawns a lot of child objects and each of them works with some global application objects e.g. registers itself in the global application registry, updates application statistics etc.
How should application transfer the ability to access those global objects to the children? Should every child inherit from static CRegistry and CStatistics or should application pass Registry and Statistics to child at the moment of creation?
Thanks.
|
It would seem very odd to inherit from CRegistry - the child objects aren't just specialized registries, are they? Their interaction with the registry is just to register themselves and then be found within the registry, I'd imagine. Ditto statistics.
It certainly sounds to me like the registry and statistics should just be passed in as appropriate (e.g. into the constructor). You may well not even need to keep the registry as a member variable, if the object just needs to register and then be found later.
If this really is a single, global registry then it might be a good time to use the singleton pattern - although that tends to make testing harder, in my experience.
Alternatively, could whatever's creating the objects register them? Should it really be the child object's job?
|
468,486
| 468,558
|
Warning C4099: type name first seen using 'class' now seen using 'struct' (MS VS 2k8)
|
Is this warning anything to worry about? I've read that it can cause erratic behaviour?
It's an example I'm trying to compile, could someone explain to me why the author declares the object as a class but then typedef's it to a structure? Is it perfectly normal to do so if the class is POD?
Thanks.
|
This warning appears when you have a one type declaration that contradicts another (one says "class", the other says "struct"). Given the one definition rule, all declarations except for at most one must be forward declarations. The warning will generally indicate that a forward declaration of a type is wrong and is usually a simple typo and should be fixed. In this case there should be no side effects, but you really should fix it.
There can be, however, some very nasty things happen if you have type name clashes (perhaps caused by using "using namespace" clauses or global namespace pollution). These warnings could be indicating that you are mixing headers from two different libraries and the type names have clashes. Code compiled under these conditions could do some very unexpected things.
My advice - understand why the warning has appeared and fix it. If the warning is in a third party product, insist that they fix it.
|
468,956
| 468,981
|
How to get C++ object name in run time?
|
Can I get an object's name in run time (like getting an object's type via RTTI)? I want the object to be able to print its name.
|
Its not possible. For on thing, an object doesn't have a unique name.
A a;
A& ar = a; // both a and ar refer to the same object
new A; // the object created doesn't have a name
A* ap = new A[100]; // either all 100 objects share the same name, or need to
// know that they are part of an array.
Your best bet is to add a string argument to the objects constructor, and give it a name when its created.
|
469,152
| 471,306
|
Using ShellExecuteEx and capturing standard in/out/err
|
I'm using ShellExecuteEx to execute a command in C. Is there a way to use ShellExecuteEx and capture standard in/out/err?
Note: I don't want to use CreateProcess.
|
As mentioned by pilif and Bob, you need to use CreateProcess.
If you want code that wraps it all up for you, I do have a class for this exact issue at:
http://code.google.com/p/kgui/source/browse/trunk/kguithread.cpp.
The class (kGUICallThread) handles Linux, macOS and Windows versions. The code is licensed LGPL.
|
469,401
| 469,836
|
Lazy object creation in C++, or how to do zero-cost validation
|
I've stumbled across this great post about validating parameters in C#, and now I wonder how to implement something similar in C++. The main thing I like about this stuff is that is does not cost anything until the first validation fails, as the Begin() function returns null, and the other functions check for this.
Obviously, I can achieve something similar in C++ using Validate* v = 0; IsNotNull(v, ...).IsInRange(v, ...) and have each of them pass on the v pointer, plus return a proxy object for which I duplicate all functions.
Now I wonder whether there is a similar way to achieve this without temporary objects, until the first validation fails. Though I'd guess that allocating something like a std::vector on the stack should be for free (is this actually true? I'd suspect an empty vector does no allocations on the heap, right?)
|
Other than the fact that C++ does not have extension methods (which prevents being able to add in new validations as easily) it should be too hard.
class Validation
{
vector<string> *errors;
void AddError(const string &error)
{
if (errors == NULL) errors = new vector<string>();
errors->push_back(error);
}
public:
Validation() : errors(NULL) {}
~Validation() { delete errors; }
const Validation &operator=(const Validation &rhs)
{
if (errors == NULL && rhs.errors == NULL) return *this;
if (rhs.errors == NULL)
{
delete errors;
errors = NULL;
return *this;
}
vector<string> *temp = new vector<string>(*rhs.errors);
std::swap(temp, errors);
}
void Check()
{
if (errors)
throw exception();
}
template <typename T>
Validation &IsNotNull(T *value)
{
if (value == NULL) AddError("Cannot be null!");
return *this;
}
template <typename T, typename S>
Validation &IsLessThan(T valueToCheck, S maxValue)
{
if (valueToCheck < maxValue) AddError("Value is too big!");
return *this;
}
// etc..
};
class Validate
{
public:
static Validation Begin() { return Validation(); }
};
Use..
Validate::Begin().IsNotNull(somePointer).IsLessThan(4, 30).Check();
|
469,477
| 472,350
|
Find nearest points in a vector
|
Given a sorted vector with a number of values, as in the following example:
std::vector<double> f;
f.pushback(10);
f.pushback(100);
f.pushback(1000);
f.pushback(10000);
I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the value "45", I'd like this to return "10" and "100".
I was looking at lower_bound and upper_bound, but they don't do what I want. Can you help?
EDIT: I've decided to post my own anser, as it is somewhat a composite of all the helpful answers that I got in this thread. I've voted up those answers which I thought were most helpful.
Thanks everyone,
Dave
|
I'm going to post my own anser, and vote anyone up that helped me to reach it, since this is what I'll use in the end, and you've all helped me reach this conclusion. Comments are welcome.
std::pair<value_type, value_type> GetDivisions(const value_type& from) const
{
if (m_divisions.empty())
throw 0; // Can't help you if we're empty.
std::vector<value_type>::const_iterator it =
std::lower_bound(m_divisions.begin(), m_divisions.end(), from);
if (it == m_divisions.end())
return std::make_pair(m_divisions.back(), m_divisions.back());
else if (it == m_divisions.begin())
return std::make_pair(m_divisions.front(), m_divisions.front());
else
return std::make_pair(*(it - 1), *(it));
}
|
469,508
| 500,389
|
Visual Studio Compiler warning C4250 ('class1' : inherits 'class2::member' via dominance)
|
The following code generates warning C4250. My question is, what's the best solution to it?
class A
{
virtual void func1();
}
class B : public A
{
}
class C : public A
{
virtual void func1();
}
class D : public B, public C
{
}
int main()
{
D d;
d.func1(); // Causes warning
}
According to what I've read it should be possible to do this:
class D : public B, public C
{
using B::func1();
}
But, this doesn't actually do anything. The way I've currently solved it is:
class D : public B, public C
{
virtual void func1() { B::func1(); }
}
What's everyone's view on this?
|
I had the same warning for the following code:
class Interface
{
public:
virtual void A() = 0;
};
class Implementation : public virtual Interface
{
public:
virtual void A() {};
};
class ExtendedInterface : public virtual Interface
{
virtual void B() = 0;
};
class ExtendedImplementation : public ExtendedInterface , public Implementation
{
public:
virtual void B() {};
};
This bug report for Visual C++ 2005 in msdn suggests that this is a known bug that was considered not important enough to fix... They suggest to disable the warning in this case by using a pragma. I think it is safe also in your case, but you should use virtual inheritance as shown in the answer by Gal Goldman.
|
469,597
| 469,613
|
Destruction order of static objects in C++
|
Can I control the order static objects are being destructed?
Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object?
|
The static objects are destructed in the reverse order of construction. And the order of construction is very hard to control. The only thing you can be sure of is that two objects defined in the same compilation unit will be constructed in the order of definition. Anything else is more or less random.
|
469,722
| 469,841
|
What advantage does C++ have over .NET when it comes to to game development and apps like VirtualBox
|
This is an attempt to rephrase a question I asked earlier. I'd like to know why C++ seems to be the language of choice for certain thick client apps. The easiest example I can think of is video games and my favorite app VirtualBox.
Please don't close this post I'm just trying to understand why this is the case.
|
As a profesional game dev working on AAA titles I can tell you. Reason number 1 is C++ and C will compile and run on any platform say a PS3 or an NDS. Next platform makers only provide robust C libraries to interface with hardware. The reason behind this is C and C++ are free, and not owned by one corporation, and because they were designed for close to the metal low level programming. This means game devs need to know C/C++ which forms a feedback loop. However many devs nowadays make their toolsets in C# or Java, but that's because performance isn't critical.
Now this posture might seem fanatic to most web developers, but games need to process entire slices of complex simulations and rendering upto 60 times per second, few web apps are bound to stay within that latency rate, so the needs are different.And same reason few web services are produced with C++.
However high level AI, and gameplay( the rules ) are scripted because of the development speed increase and ability to fine tune the game. Also because this amounts to about roughly 15% of the resources, so we can splurge here, and let the designers do their job. Also note that coding a fexible rule system would take about the same resources anyways even if done in C++. Oh and not all platforms allow Jit code which would be nice :)
And of course as mentioned memory control, if you use even 1 byte more memory than provided by the hardware, it doesn't slow down like a PC. It crashes. So we love our naked pointers, custom allocators and RAII.
|
469,751
| 470,200
|
Winform Not Displaying in Designer
|
I have a Managed C++ WinForm that suddenly stopped showing in the VS 2005 designer. The error it shows is
Could not find type 'int'. Please
make sure that the assembly that
contains this type is referenced. If
this type is a part of your
development project, make sure that
the project has been successfully
built.
I don't even know where to start with this one. Does the designer only access the InitializeComponent(void) method when rendering the form? So my question is: where do you start troubleshooting designer errors?
EDIT: I forgot to mention that this code builds and runs perfectly. It only shows an error in the windows forms designer.
|
This is troubleshooting for C# but I'd assume a couple of the points mentioned here would help.
What's the state of play with "Visual Inheritance"
|
469,849
| 469,861
|
Using an STL Iterator without initialising it
|
I would like to do something like this:
container::iterator it = NULL;
switch ( eSomeEnum )
{
case Container1:
it = vecContainer1.begin();
break;
case Container2:
it = vecContainer2.begin();
break;
...
}
for( ; it != itEnd ; ++it )
{
..
}
But I can't create and initialise an iterator to NULL. Is there some way I can do this? Ideally I would just create and assign the iterator in the switch, but then it would go out of scope immediately.
|
You just needn't initialize it at all, because iterators are DefaultConstructible.
|
469,892
| 470,451
|
C++ Why is this passed-by-reference array generating a runtime error?
|
void pushSynonyms (string synline, char matrizSinonimos [1024][1024]){
stringstream synstream(synline);
vector<int> synsAux;
int num;
while (synstream >> num) {synsAux.push_back(num);}
int index=0;
while (index<(synsAux.size()-1)){
int primerSinonimo=synsAux[index];
int segundoSinonimo=synsAux[++index];
matrizSinonimos[primerSinonimo][segundoSinonimo]='S';
matrizSinonimos [segundoSinonimo][primerSinonimo]='S';
}
}
and the call..
char matrizSinonimos[1024][1024];
pushSynonyms("1 7", matrizSinonimos)
It's important for me to pass matrizSinonimos by reference.
Edit: took away the & from &matrizSinonimos.
Edit: the runtime error is:
An unhandled win32 exception occurred in program.exe [2488]![alt text][1]
|
What's wrong with it
The code as you have it there - i can't find a bug. The only problem i spot is that if you provide no number at all, then this part will cause harm:
(synsAux.size()-1)
It will subtract one from 0u . That will wrap around, because size() returns an unsigned integer type. You will end up with a very big value, somewhere around 2^16 or 2^32. You should change the whole while condition to
while ((index+1) < synsAux.size())
You can try looking for a bug around the call side. Often it happens there is a buffer overflow or heap corruption somewhere before that, and the program crashes at a later point in the program as a result of that.
The argument and parameter stuff in it
Concerning the array and how it's passed, i think you do it alright. Although, you still pass the array by value. Maybe you already know it, but i will repeat it. You really pass a pointer to the first element of this array:
char matrizSinonimos[1024][1024];
A 2d array really is an array of arrays. The first lement of that array is an array, and a pointer to it is a pointer to an array. In that case, it is
char (*)[1024]
Even though in the parameter list you said that you accept an array of arrays, the compiler, as always, adjusts that and make it a pointer to the first element of such an array. So in reality, your function has the prototype, after the adjustments of the argument types by the compiler are done:
void pushSynonyms (string synline, char (*matrizSinonimos)[1024]);
Although often suggested, You cannot pass that array as a char**, because the called function needs the size of the inner dimension, to correctly address sub-dimensions at the right offsets. Working with a char** in the called function, and then writing something like matrizSinonimos[0][1], it will try to interpret the first sizeof(char**) characters of that array as a pointer, and will try to dereference a random memory location, then doing that a second time, if it didn't crash in between. Don't do that. It's also not relevant which size you had written in the outer dimension of that array. It rationalized away. Now, it's not really important to pass the array by reference. But if you want to, you have to change the whole thingn to
void pushSynonyms (string synline, char (&matrizSinonimos)[1024][1024]);
Passing by reference does not pass a pointer to the first element: All sizes of all dimensions are preserved, and the array object itself, rather than a value, is passed.
|
470,040
| 470,053
|
boost::bind with functions that have parameters that are references
|
I noticed that when passing reference parameters to boost bind, those parameters won't act like references. Instead boost creates another copy of the member and the original passed in variable remains unchanged.
When I change the references to pointers, everything works ok.
My question is:
Is it possible to get references to work, or at least give a compiling error when it tries to use reference parameters?
|
The boost documentation for bind suggests that you can use boost::ref and boost::cref for this.
|
470,388
| 470,411
|
My C++ object file is too big
|
I am working on a C++ program and the compiled object code from a single 1200-line file (which initializes a rather complex state machine) comes out to nearly a megabyte. What could be making the file so large? Is there a way I can find what takes space inside the object file?
|
There can be several reasons when object files are bigger than they have to be at minimum:
statically including dependent libraries
building with debug information
building with profiling information
creating (extremely) complex data structures using templates (maybe recursive boost-structures)
not turning on optimizing flags while compiling (saves not that much and can cause difficulties if used too extremely)
At first I suggest to check if you're building with debug information, this causes the most bloat in my experience.
|
470,544
| 470,563
|
Compilation error when calling _tcsstr and assigning to a wchar_t*
|
I am getting a compilation error when trying to build a C++ project which previously worked.
The code follows:
const wchar_t* pdest;
pdest = _tcsstr(ConnStr, Name);
The error follows:
Error 10 error C2440: '=' : cannot convert from 'const char *' to 'const wchar_t
I'm using Visual Studio 2008. The error message explains the problem well, but I know this program used to compile, what am I doing wrong?
|
Your code is dangerous. _tcsstr is a TCHAR macro, so it's definition can change depending on whether or not UNICODE is defined. wchar_t is fixed. The error you're seeing is due to this exact problem - the environment is using the single-byte version of _tcsstr (likely becasue UNICODE is not defined).
Don't just define UNICODE. Fix the code first. Either use TCHAR macros for both, or the wide character functions.
|
470,835
| 476,403
|
A C++ iterator adapter which wraps and hides an inner iterator and converts the iterated type
|
Having toyed with this I suspect it isn't remotely possible, but I thought I'd ask the experts. I have the following C++ code:
class IInterface
{
virtual void SomeMethod() = 0;
};
class Object
{
IInterface* GetInterface() { ... }
};
class Container
{
private:
struct Item
{
Object* pObject;
[... other members ...]
};
std::list<Item> m_items;
};
I want to add these methods to Container:
MagicIterator<IInterface*> Begin();
MagicIterator<IInterface*> End();
In order that callers can write:
Container c = [...]
for (MagicIterator<IInterface*> i = c.Begin(); i != c.End(); i++)
{
IInterface* pItf = *i;
[...]
}
So essentially I want to provide a class which appears to be iterating over some collection (which the caller of Begin() and End() is not allowed to see) of IInterface pointers, but which is actually iterating over a collection of pointers to other objects (private to the Container class) which can be converted into IInterface pointers.
A few key points:
MagicIterator is to be defined outside Container.
Container::Item must remain private.
MagicIterator has to iterate over IInterface pointers, despite the fact that Container holds a std::list<Container::Item>. Container::Item contains an Object*, and Object can be used to fetch IInterface*.
MagicIterator has to be reusable with several classes which resemble Container, but might internally have different list implementations holding different objects (std::vector<SomeOtherItem>, mylist<YetAnotherItem>) and with IInterface* obtained in a different manner each time.
MagicIterator should not contain container-specific code, though it may delegate to classes which do, provided such delegation is not hard coded to to particular containers inside MagicIterator (so is somehow resolved automatically by the compiler, for example).
The solution must compile under Visual C++ without use of other libraries (such as boost) which would require a license agreement from their authors.
Also, iteration may not allocate any heap memory (so no new() or malloc() at any stage), and no memcpy().
Thanks for your time, even if you're just reading; this one's really been bugging me!
Update: Whilst I've had some very interesting answers, none have met all the above requirements yet. Notably the tricky areas are i) decoupling MagicIterator from Container somehow (default template arguments don't cut it), and ii) avoiding heap allocation; but I'm really after a solution which covers all of the above bullets.
|
I've now found a solution which is fitter for my original purpose. I still don't like it though :)
The solution involves MagicIterator being templated on IInterface* and being constructed with both a void* to an iterator, the byte size of said iterator, and a table of pointers to functions which perform standard iteration functions on said void* such as increment, decrement, dereference, etc. MagicIterator assumes that it is safe to memcpy the given iterator into an internal buffer, and implements its own members by passing its own buffer as a void* to the supplied functions as if it were the original iterator.
Container then has to implement static iteration functions which cast back a supplied void* to a std::list::iterator. Container::begin() and Container::end() simply construct a std::list::iterator, pass a pointer to it into a MagicIterator along with a table of its iteration functions, and return the MagicIterator.
It's somewhat disgusting, and breaks my original rule regarding "no memcpy()", and makes assumptions about the internals of the iterators in question. But it avoids heap allocation, keeps Collection's internals (including Item) private, renders MagicIterator entirely independent of the collection in question and of IInterface*, and in theory allows MagicIterators to work with any collection (provided its iterators can be safely memcopy()'d).
|
470,840
| 471,182
|
How do I resolve LNK1104 error with Boost Filesystem Library in MSCV?
|
I am having trouble getting my project to link to the Boost (version 1.37.0) Filesystem lib file in Microsoft Visual C++ 2008 Express Edition. The Filesystem library is not a header-only library. I have been following the Getting Started on Windows guide posted on the official boost web page. Here are the steps I have taken:
I used bjam to build the complete set of lib files using:
bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete
I copied the /libs directory (located in C:\Program Files\boost\build-boost\boost\bin.v2) to C:\Program Files\boost\boost_1_37_0\libs.
In Visual C++, under Project > Properties > Additional Library Directories I added these paths:
C:\Program Files\boost\boost_1_37_0\libs
C:\Program Files\boost\boost_1_37_0\libs\filesystem\build\msvc-9.0express\debug\link-static\threading-multi
I added the second one out of desperation. It is the exact directory where libboost_system-vc90-mt-gd-1_37.lib resides.
In Configuration Properties > C/C++ > General > Additional Include Directories I added the following path:
C:\Program Files\boost\boost_1_37_0
Then, to put the icing on the cake, under Tools > Options VC++ Directories > Library files, I added the same directories mentioned in step 3.
Despite all this, when I build my project I get the following error:
fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib'
Additionally, here is the code that I am attempting to compile as well as a screen shot of the aformentioned directory where the (assumedly correct) lib file resides:
#include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations
#include <iostream> // for std::cout
using boost::filesystem; // for ease of tutorial presentation;
// a namespace alias is preferred practice in real code
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
|
Ferruccio's answer contains most of the insight. However, Pukku made me realize my mistake. I am posting my own answer to give a full explanation. As Ferruccio explained, Filesystem relies on two libraries. For me, these are:
libboost_system-vc90-mt-gd-1_37.lib
libboost_filesystem-vc90-mt-gd-1_37.lib
I must not have noticed that when I supplied the directory for libboost_filesystem-vc90-mt-gd-1_37.lib, the error output changed from
fatal error LNK1104: cannot open file 'libboost_filesystem-vc90-mt-gd-1_37.lib'
to
fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib'
Causing me to think that the error was persisting. This lead me to post some rather inaccurate information. Also, after reading that Filesystem requires two libraries, I now see the significance of the keyword stage for the bjam command. Supplying
bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete stage
Causes bjam to place an additional directory, aptly named stage, in the boost_1_37_0 directory. This folder contains a folder named /lib, which has copies of all of the lib files in one place. This is convenient for Visual C++ because you can supply it with this single directory and it will take care of all of the dependencies.
|
471,198
| 471,389
|
Is there any good example of http upload using WinInet c++ library
|
I cannot get my code to work :/
|
Here's a quick example from Microsoft.
static TCHAR hdrs[] =
_T("Content-Type: application/x-www-form-urlencoded");
static TCHAR frmdata[] =
_T("name=John+Doe&userid=hithere&other=P%26Q");
static LPSTR accept[2]={"*/*", NULL};
// for clarity, error-checking has been removed
HINTERNET hSession = InternetOpen("MyAgent",
INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession, _T("ServerNameHere"),
INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequest(hConnect, "POST",
_T("FormActionHere"), NULL, NULL, accept, 0, 1);
HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
// close any valid internet-handles
The example comes from here.
|
471,228
| 471,243
|
error: conversion from long int to non-scalar type, comparing an iterator to null
|
Hello I hope someone can explain this problem. This is the code:
class Memory{
public:
PacketPtr pkt;
MemoryPort* port;
MemCtrlQueueEntry(){};
};
And after I do:
std::list<Memory*>::iterator lastIter = NULL;
And I get the following error:
error: conversion from long int to non-scalar type std::_List_iterator<DRAMMemory::MemCtrlQueueEntry*> requested
Where is the problem, of initializing the iterator to NULL?.
|
Iterators are not pointers. If you want to initialize them to a non-value, use list::end(). The fact that vector<T>::iterator is sometime implemented with a pointer is an implementation detail that you cannot depend on.
If you want to assign NULL to the value at the location that the iterator is refering to, you have to dereference it first:
std::list<Memory *> aList;
aList.push_back(new Memory())
std::list<Memory*>::iterator listIter = aList.begin();
delete *listIter;
*listIter = NULL;
Initializing with list::end():
std::list<Memory *> aList;
std::list<Memory*>::iterator listIter = aList.end();
|
471,265
| 473,105
|
Importing png Files in Visual studio C++ Resource Editor
|
I would like to be able to import png file inside of Visual Studio Resource Editor so as to be able to use the embedded resource in different other projects . Is there a solution for that? I know that it works for bitmaps but i am interested in the pngs because of the "transparency" that is availble even on lower format [16x16] or [32x32] (but lacks for bitmaps).
Any ideas?
Thank you.
|
With VS 2008 you can import pngs and they will be recognized as an image, ie you will able to "see" it, but you will not be able to modify with within the resource editor.
But anyway the problem is that they will no be treated as bitmaps, so you can't embedded it inside a dialog. But you can access it with the usual FindResource/LockResource.
Also as MFC relies on GDI and it doesn't support natively PNG (at least on XP, I didn't try on Vista or Win7) you will need to convert them to BMP anyway. Here Gdi+ can be helpful.
Also I didn't check on VS 2010, perhaps worth a try if it have a better C++ resource editor.
|
471,344
| 471,718
|
Guaranteed file deletion upon program termination (C/C++)
|
Win32's CreateFile has FILE_FLAG_DELETE_ON_CLOSE, but I'm on Linux.
I want to open a temporary file which will always be deleted upon program termination. I could understand that in the case of a program crash it may not be practical to guarantee this, but in any other case I'd like it to work.
I know about RAII. I know about signals. I know about atexit(3). I know I can open the file and delete it immediately and the file will remain accessible until the file descriptor is closed (which even handles a crash). None of these seem like a complete and straightforward solution:
RAII: been there, done that: I have an object whose destructor deletes the file, but the destructor is not called if the program is terminated by a signal.
signals: I'm writing a low-level library which makes registering a signal handler a tricky proposition. For example, what if the application uses signals itself? I don't want to step on any toes. I might consider some clever use of sigaction(2) to cope...but haven't put enough thought into this possibility yet.
atexit(3): apparently useless, since it isn't called during abnormal termination (e.g. via a signal).
preemptive unlink(2): this is pretty good except that I need the file to remain visible in the filesystem (otherwise the system is harder to monitor/troubleshoot).
What would you do here?
Further Explanation
I elided one detail in my original post which I now realize I should have included. The "file" in this case is not strictly a normal file, but rather is a POSIX Message Queue. I create it via mq_open(). It can be closed via mq_close() or close() (the former is an alias for the latter on my system). It can be removed from the system via mq_unlink(). All of this makes it analogous to a regular file, except that I cannot choose the directory in which the file resides. This makes the current most popular answer (placing the file in /tmp) unworkable, because the "file" is created by the system in a virtual filesystem with very limited capacity. (I've mounted the virtual filesystem in /dev/mqueue, following the example in man mq_overview) .
This also explains why I need the name to remain visible (making the immediate-unlink approach unworkable): the "file" must be shared between two or more processes.
|
The requirement that the name remains visible while the process is running makes this hard to achieve. Can you revisit that requirement?
If not, then there probably isn't a perfect solution. I would consider combining a signal handling strategy with what Kamil Kisiel suggests. You could keep track of the signal handlers installed before you install your signal handlers. If the default handler is SIG_IGN, you wouldn't normally install your own handler; if it is SIG_DFL, you would remember that; if it is something else - a user-defined signal handler - you would remember that pointer, and install your own. When your handler was called, you'd do whatever you need to do, and then call the remembered handler, thus chaining the handlers. You would also install an atexit() handler. You would also document that you do this, and the signals for which you do it.
Note that signal handling is an imperfect strategy; SIGKILL cannot be caught, and the atexit() handler won't be called, and the file will be left around.
David Segond's suggestion - a temporary file name daemon - is interesting. For simple processes, it is sufficient; if the process requesting the temporary file forks and expects the child to own the file thereafter (and exits) then the daemon has a problem detecting when the last process using it dies - because it doesn't automatically know the processes that have it open.
|
471,432
| 471,461
|
In which scenario do I use a particular STL container?
|
I've been reading up on STL containers in my book on C++, specifically the section on the STL and its containers. Now I do understand each and every one of them have their own specific properties, and I'm close to memorizing all of them... But what I do not yet grasp is in which scenario each of them is used.
What is the explanation? Example code is much prefered.
|
This cheat sheet provides a pretty good summary of the different containers.
See the flowchart at the bottom as a guide on which to use in different usage scenarios:
Created by David Moore and licensed CC BY-SA 3.0
|
471,438
| 822,520
|
shared_ptr in std::tr1
|
I am working on a platform with a gcc compiler however boost cannot compile on it.
I am wondering what is the proper way to include the shared_ptr in std:tr1 on gcc? the file i looked in said not to include it directly, from what i can tell no other file includes it either :|
|
In G++ 4.3,
#include <tr1/memory>
should do the trick. You'll find shared_ptr at std::tr1::shared_ptr.
|
472,015
| 472,028
|
new on stack instead of heap (like alloca vs malloc)
|
Is there a way to use the new keyword to allocate on the stack (ala alloca) instead of heap (malloc) ?
I know I could hack up my own but I'd rather not.
|
To allocate on the stack, either declare your object as a local variable by value, or you can actually use alloca to obtain a pointer and then use the in-place new operator:
void *p = alloca(sizeof(Whatever));
new (p) Whatever(constructorArguments);
However, while using alloca and in-place new ensures that the memory is freed on return, you give up automatic destructor calling. If you're just trying to ensure that the memory is freed upon exit from the scope, consider using std::auto_ptr<T> or some other smart pointer type.
|
472,329
| 472,365
|
How can I synchronize two processes accessing a file on a NAS?
|
Here's the thing: I have two applications, written in C++ and running on two machines with different OS (one Linux and one Windows). One of this process is in charge of updating an XML file on a NAS (Network Attached Storage) while the other one reads this file.
Is it possible to synchronize these two processes in order to avoid reading of the file at the same time it's being modified?
|
You could create a lock file on the server that is created before you do a write, wait then write and delete on completion., Have the read process check for the token before reading the file.
Edit: To address the comments, you can implement a double-checked locking type pattern. Have both reader and writer have a locking file and double check before you do work, something like:
Reader: Check for write lock file, create read lock file, check for write lock file, if exists delete read file and abort.
Writer: Check for read lock file, create write lock file, check for read lock file, if exists delete write lock file and abort.
This will stop your processes trampling on each other but a potential race condition may occur in that the you could potentially have both processes check, create then recheck simultaneously though this will not cause the data to be read in an inconsistent state but will cause both read and write processes to abort for your specified delay
|
472,393
| 472,399
|
Cache, loops and performance
|
Some time ago I wrote a little piece of code to ask about on interviews and see how people understand concepts of cache and memory:
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <iostream>
#define TOTAL 0x20000000
using namespace std;
__int64 count(int INNER, int OUTER)
{
int a = 0;
int* arr = (int*) HeapAlloc(GetProcessHeap(), 0, INNER * sizeof(int));
if (!arr) {
cerr << "HeapAlloc failed\n";
return 1;
}
LARGE_INTEGER freq;
LARGE_INTEGER startTime, endTime;
__int64 elapsedTime, elapsedMilliseconds;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&startTime);
/* Начало работы */
for (int i = 0; i < OUTER; i++) {
for (int j = 0; j < INNER; j++) {
a |= i;
arr[j] = a;
}
}
/* Конец работы */
QueryPerformanceCounter(&endTime);
elapsedTime = endTime.QuadPart - startTime.QuadPart;
elapsedMilliseconds = (1000 * elapsedTime) / freq.QuadPart;
HeapFree(GetProcessHeap(), 0, arr);
return elapsedMilliseconds;
}
int _tmain(int argc, _TCHAR* argv[])
{
__int64 time;
for (int INNER = 0x10; INNER <= 0x2000000; INNER <<= 1) {
int OUTER = TOTAL / INNER;
time = count(INNER, OUTER);
cout << INNER << "\t" << OUTER << "\t" << time << "\n";
}
}
That's what it compiles to (the loop itself):
00401062 xor ecx,ecx
00401064 test ebp,ebp
00401066 jle count+83h (401083h)
00401068 xor eax,eax
0040106A test ebx,ebx
0040106C jle count+7Ch (40107Ch)
0040106E mov edi,edi
00401070 or esi,ecx
00401072 mov dword ptr [edi+eax*4],esi
00401075 add eax,1
00401078 cmp eax,ebx
0040107A jl count+70h (401070h)
0040107C add ecx,1
0040107F cmp ecx,ebp
00401081 jl count+68h (401068h)
That's what the program outputs on my machine:
LOG2(INNER) LOG2(OUTER) Time, ms
4 25 523
5 24 569
6 23 441
7 22 400
8 21 367
9 20 358
10 19 349
11 18 364
12 17 378
13 16 384
14 15 357
15 14 377
16 13 379
17 12 390
18 11 386
19 10 419
20 9 995
21 8 1,015
22 7 1,038
23 6 1,071
24 5 1,082
25 4 1,119
I ask people to explain what's going on. As inner array grows, the number of cycles decreases, as the time does. As inner array outgrows the cache, cache misses begin to happen and time raises. It's all right so far.
BUT: when the INNER array size is 16 (that gives us 64 bytes of data), there is little performance boost, despite the greater number of jmps in code. It's little (523 vs. 569), but reproducible.
The question is: why this boost?
|
Probably because 64 is the cache line size on your machine, and you basically run each iteration fully out of a single cache line.
|
472,530
| 472,750
|
How to pass an array size as a template with template type?
|
My compiler behaves oddly when I try to pass a fixed-size array to a template function. The code looks as follows:
#include <algorithm>
#include <iostream>
#include <iterator>
template <typename TSize, TSize N>
void f(TSize (& array)[N]) {
std::copy(array, array + N, std::ostream_iterator<TSize>(std::cout, " "));
std::cout << std::endl;
}
int main() {
int x[] = { 1, 2, 3, 4, 5 };
unsigned int y[] = { 1, 2, 3, 4, 5 };
f(x);
f(y); //line 15 (see the error message)
}
It produces the following compile error in GCC 4.1.2:
test.cpp|15| error: size of array has non-integral type ‘TSize’
test.cpp|15| error: invalid initialization of reference of type
‘unsigned int (&)[1]’ from expression of type ‘unsigned int [5]’
test.cpp|6| error: in passing argument 1 of ‘void f(TSize (&)[N])
[with TSize = unsigned int, TSize N = ((TSize)5)]’
Note that the first call compiles and succeeds. This seems to imply that while int is integral, unsigned int isn't.
However, if I change the declaration of my above function template to
template <typename TSize, unsigned int N>
void f(TSize (& array)[N])
the problem just goes away! Notice that the only change here is from TSize N to unsigned int N.
Section [dcl.type.simple] in the final draft ISO/IEC FDIS 14882:1998 seems to imply that an "integral type" is either signed or unsigned:
The signed specifier forces char objects and bit-fields to be signed; it is redundant with other integral types.
Regarding fixed-size array declarations, the draft says [dcl.array]:
If the constant-expression (expr.const) is present, it shall be an integral constant expression and its value shall be greater than zero.
So why does my code work with an explicit unsigned size type, with an inferred signed size type but not with an inferred unsigned size type?
EDIT Serge wants to know where I'd need the first version. First, this code example is obviously simplified. My real code is a bit more elaborate. The array is actually an array of indices/offsets in another array. So, logically, the type of the array should be the same as its size type for maximum correctness. Otherwise, I might get a type mismatch (e.g. between unsigned int and std::size_t). Admittedly, this shouldn't be a problem in practice since the compiler implicitly converts to the larger of the two types.
EDIT 2 I stand corrected (thanks, litb): size and offset are of course logically different types, and offsets into C arrays in particular are of type std::ptrdiff_t.
|
Hmm, the Standard says in 14.8.2.4 / 15:
If, in the declaration of a function template with a non-type template-parameter, the non-type template-parameter is used in an expression in the function parameter-list and, if the corresponding template-argument is deduced, the template-argument type shall match the type of the template-parameter exactly, except that a template-argument deduced from an array bound may be of any integral type.
Providing this example:
template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
A<1> a;
f(a); // error: deduction fails for conversion from int to short
f<1>(a); // OK
}
That suggests that the compilers that fail to compile your code (apparently GCC and Digital Mars) do it wrong. I tested the code with Comeau, and it compiles your code fine. I don't think there is a different to whether the type of the non-type template parameter depends on the type of the type-parameter or not. 14.8.2.4/2 says the template arguments should be deduced independent from each other, and then combined into the type of the function-parameter. Combined with /15, which allows the type of the dimension to be of different integral type, i think your code is all fine. As always, i take the c++-is-complicated-so-i-may-be-wrong card :)
Update: I've looked into the passage in GCC where it spits out that error message:
...
type = TREE_TYPE (size);
/* The array bound must be an integer type. */
if (!dependent_type_p (type) && !INTEGRAL_TYPE_P (type))
{
if (name)
error ("size of array %qD has non-integral type %qT", name, type);
else
error ("size of array has non-integral type %qT", type);
size = integer_one_node;
type = TREE_TYPE (size);
}
...
It seems to have missed to mark the type of the size as dependent in an earlier code block. As that type is a template parameter, it is a dependent type (see 14.6.2.1).
Update: GCC developers fixed it: Bug #38950
|
472,667
| 472,683
|
Lambda expressions support in VS2008 SP1
|
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something?
#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
cout << endl;
}
Thank you in advance.
|
See Stackoverflow question #146381
Simply put: no. Visual Studio 2010 will support C++0x to some extent, but I'm unsure if that will include lambda expressions.
|
472,791
| 473,353
|
How to create a filled arrow CustomLineCap?
|
The MSDN documentation has several open arrow examples but no examples for filled arrows.
I just want to create a bigger arrow than the default LineCapArrowAnchor. I tried several things and can't get it to work. It should be simple, right?
|
Found it. Looks like there's an AdjustableArrowCap class that derives from CustomLineCap and does just what I wanted.
|
473,023
| 473,613
|
Have you ever obtained a significant speedup by using boost::pool?
|
I've played with boost::pool a few times in places where it seemed to me I was seriously hammering the heap with a lot of object "churn". Generally I've used boost::object_pool, or boost::pool_alloc as an STL template parameter. However the result is invariably that performance is virtually unchanged, or significantly worsened.
I'm curious to hear of any success stories with it.
What sort of things should I look for in profiling output which might indicate boost::pool is likely to help ?
Is it just actually pretty hard to improve on good old malloc ?
|
Memory pools are most effective imo for transaction style processing where you can allocate to the pool and then when the transaction is done, just dump it into oblivion. The real speed up isn't that each allocation is going to be much faster its that you will have near zero memory fragmentation in an extremely long running application.
In sort, it sounds like your applications do not warrant using memory pools
|
473,236
| 473,262
|
Check for value definedness in C++
|
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:
class Foo {
public:
double get_bar();
private:
double bar;
void calculate_bar() {
bar = something();
}
};
double Foo::get_bar() {
if ( undefined(bar) )
calculate_bar();
return bar;
}
Is it possible in C++?
Thanks
|
As the other answers says, C++ doesn't have this concept. You can easily work around it though.
Either you can have an undefined value which you initialize bar to in the constructor, typically -1.0 or something similar.
If you know that calculate_bar never returns negative values you can implement the undefined function as a check for < 0.0.
A more general solution is having a bool saying whether bar is defined yet that you initialized to false in the constructor and when you first set it you change it to true. boost::optional does this in an elegant templated way.
This is what the code example you have would look like.
class Foo {
public:
double get_bar();
Foo() : barDefined(false) {}
private:
double bar;
bool barDefined;
void calculate_bar() {
bar = something();
}
};
double Foo::get_bar() {
if ( barDefined == false ) {
calculate_bar();
barDefined = true;
}
return bar;
}
|
473,623
| 475,660
|
Sphere World Implementation C++
|
What would be the best way to implement, store, and render spherical worlds, such as the ones in spore or infinity but without the in-between stages of spore, and multiple worlds ala infinity universe. Make no assumptions on how the planet itself is generated or its size/scale.
|
For rendering, you'll need to use some sort of level-of-detail algorithm in order to seamlessly move from close to the planet's surface to far away. There are many dynamic LOD algorithms (see here). An older algorithm, called ROAM, can be adapted to handle spherical objects, or planets (spherical ROAM). Geometry clipmaps is a newer, more popular algorithm that can be adapted to spherical surfaces as well.
As for storing the data, you may want to look into procedural generation (depending on your needs) for texturing, heightmaps, etc. This is similar to how Infinity and Spore do things. You can read a little about procedural texturing here. Procedural heightmaps are simpler, depending on how complex/realistic you want your terrain. On the simplest level, you can simply displace your vertex height by a perlin noise function.
|
473,662
| 473,677
|
I see many examples of C++ with the use of "Foo ^ bar" - what is "^"?
|
Is that .NET related?
It appears to be a pointer of some sort, what is the difference?
Edit:
I actually know it is the XOR operator, but look at this example from this page.
void objectCollection() {
using namespace System::Collections;
**ArrayList ^as = gcnew ArrayList;**
//... }
What is this?
Thanks.
|
I'm assuming that you're looking at constructs of the form:
Foo ^bar = gcnew Foo();
You're right, in .NET it is a pointer-"like" type and is part of C++/CLI, not but not standard ISO C++.
It's a reference to a garbage-collected, managed .NET object as opposed to a regular, unmanaged C++ object.
As the other poster suggest, outside the .NET world or in a non-object creation context, it is the XOR operator.
|
473,720
| 473,753
|
Why is the destructor ignored in this code?
|
The following code demonstrates a weird problem I have in a Turbo C++ Explorer project. One of the three stack objects in D::D() is not destroyed after going out of scope.
This only happens if compiled in release mode, the auto_ptrs a_ and b_ are of different types and the exception thrown doesn't inherit from std::exception. It appears to work just fine in VC++ 2005 and C++ Builder 2009. I did install the BDS2006 Update 2, the hotfix rollup and hotfix 12.
Is it my code or the compiler? Do you know of a fix? Not being able to reliably use auto_ptr in a VCL project would be quite inconvenient.
#include <memory>
#include <stdexcept>
#include <iostream>
typedef std::exception my_error; // will work fine if replaced with line below
//class my_error : public std::exception {};
class A {};
class B {};
class C
{
public:
C(int id) : id_(id) { std::cout << "C::C() " << id_ << std::endl; };
~C() { std::cout << "C::~C() " << id_ << std::endl; };
private:
int id_;
};
class D
{
public:
D()
{
C c1(1);
C c2(2);
C c3(3);
throw my_error();
};
private:
std::auto_ptr<A> a_;
std::auto_ptr<B> b_; // will work fine if replaced with line below
// std::auto_ptr<A> b_;
// std::auto_ptr<C> c_; // see expected output
};
#pragma argsused
int main(int argc, char* argv[])
{
try
{
D d;
}
catch (...)
{
std::cout << "caught exception" << std::endl;
}
return 0;
}
Expected:
C::C() 1
C::C() 2
C::C() 3
C::~C() 3
C::~C() 2
C::~C() 1
caught exception
Got:
C::C() 1
C::C() 2
C::C() 3
C::~C() 2
C::~C() 1
caught exception
Got (with line '// std::auto_ptr<C> c_;' uncommented):
C::C() 1
C::C() 2
C::C() 3
C::~C() 1
caught exception
Edit: Made suggested changes
Edit 2:
I just tested it with C++ Builder 2007 (11.0.2902.10471), which shows the same problem. The release configuration works as soon as I check the "Debug information" box in Project -> Options -> C++ Compiler -> Debugging. It surprises me that the executable gets smaller with "Debug information" enabled (down to 31.5 KB from 39.5 KB ).
Edit 3:
In Turbo C++ Explorer (C++ Builder 2006) (10.0.2288.42451) the release configuration works if I uncheck the "Inline function expansion (-vi)" box in Project -> Options -> C++ Compiler -> Debugging. Replacing the first line (#include <memory>) with the following code makes it work, too.
#pragma option push -vi-
#include <memory>
#pragma option pop
|
This appears to be a compiler bug. I just ran the same sample in VS2008SP1 and got the expected output.
|
473,915
| 473,929
|
Should I make my own framework?
|
Should I make my own framework by wrapping up the STL classes and/or Boost libraries so that if I need to change the implementation of the string, vectors, lists, etc. or I need to write functions that MFC, other other libraries or even other platforms would need to use their format, I can easily mutate them to meet the criteria. this is what I'm thinking.
// In my framework:
namespace MyFX {
typedef std::string String;
};
// Port specific (MFC in this case)
CString ToCString(const MyFx::String &str) { /* magic */ }
// Port specific (.NET specific)
System::String^ ToManagedString(const MyFx::String &str) { /* magic */ }
Am I reinventing the wheel too much?
I would use the MyFx::String in UI interfaces between the UI and the other layers.
|
It seems to me like there won't be a lot of benefit to this; in my experience, the point of using these frameworks is so that you don't go reinventing the wheel. If you find that you need to write a new string class or a new vector class, you should think really hard about it, and make sure you're not just doing something else wrong. I'm not saying there's never a reason to write your own string class, I'm just saying it's rare. Given that, I would suggest just using the desired frameworks directly.
Regarding the conversion functions, I believe the compiler won't see your ToCString function any differently than it would see this:
CString ToCString( const std::string & ) {...}
This is because a C++ typedef does not create a new type, just an alias to an existing type.
Further Thoughts
I think the concern you voice here is a very natural one, and I know it has come up in my team several times. However, I think the answer is still as stated above.
While the STL classes are probably not perfect, they were designed by very smart people, who put quite a lot of thought into the task. Thus, the odds of you needing to write a full replacement string class are very small. Furthermore, and without intending any slight, it would take you (or me) a very long time to implement a robust general-purpose string class that could suitably replace std::string.
Another possible way to think about it would be this: would you consider "replacing" the String class in Java or C#? I think the answer there is clearly "no", although there may be occasional limited areas where you use something other than a String to represent a sequence of characters. Same thing goes here: std::string is as close as C++ gets to a built-in string class, and you almost assuredly don't need to replace it.
|
473,958
| 473,974
|
Memory management in memory intensive application
|
If you are developing a memory intensive application in C++ on Windows, do you opt to write your own custom memory manager to allocate memory from virtual address space or do you allow CRT to take control and do the memory management for you ? I am especially concerned about the fragmentation caused by the allocation and deallocation of small objects on heap. Because of this, I think the process will run out of memory eventhough there is enough memory but is fragmented.
|
I think your best bet is to not implement one until profiles prove that the CRT is fragmenting memory in a way that damages the performance of your application. CRT, core OS, and STL guys spend a lot of time thinking about memory management.
There's a good chance that your code will perform quite fine under existing allocators with no changes needed. There's certainly a better chance of that, than there is of you getting a memory allocator right the first time. I've written memory allocators before for similar circumstances and it's a monsterous task to take on. Not so suprisingly, the version I inherited was rife with fragmentation problems.
The other advantage of waiting until a profile shows it's a problem is that you will also know if you've actually fixed anything. That's the most important part of a performance fix.
As long as you're using standard collection classes an algorihtmns (such as STL/BOOST) it shouldn't be very hard to plug in a new allocator later on in the cycle to fix the portions of your code base that do need to be fixed. It's very unlikely that you will need a hand coded allocator for your entire program.
|
474,007
| 474,058
|
Floating Point to Binary Value(C++)
|
I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754).
So I could take a number, and end up with a int num[16] array with the binary value of the float:
num[0] would be 1
num[1] would be 1
num[2] would be 0
num[3] would be 1
and so on...
Putting an int into an array isn't difficult, just the process of getting the binary value of a float is where I'm stuck. Can you just read the binary in the memory that the float variable? If not, how could I go about doing this in C++?
EDIT: The reason for doing the comparison this way is that I am wanting to learn to do bitwise operations in C++.
|
Use union and bitset:
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
union
{
float input; // assumes sizeof(float) == sizeof(int)
int output;
} data;
data.input = 2.25125;
std::bitset<sizeof(float) * CHAR_BIT> bits(data.output);
std::cout << bits << std::endl;
// or
std::cout << "BIT 4: " << bits[4] << std::endl;
std::cout << "BIT 7: " << bits[7] << std::endl;
}
It may not be an array but you can access bits with [] operator as if you were using an array.
Output
$ ./bits
01000000000100000001010001111011
BIT 4: 1
BIT 7: 0
|
474,279
| 474,378
|
Retaining functors as variables
|
I'm working on a resource management class and want to have the user provide a functor to a "ReleaseResource" method as part of the resource manager's constructor. From there when a resource is requested that functor will be provided as the deleter for the shared_ptr that I will be returning so that the appropriate method will be called when the resource is no longer used.
The problem I'm running into that this requires me to store the functor in my class, and I'm not entirely sure how to do that. Typically when using a functor you template the function like so:
template<class MyFunctor> MyMethod(MyFunctor f) {
f();
}
Which is great if you intend to use the functor in the scope of that function, but since the template goes out of scope with the function I'm not sure how you would specify a variable of the appropriate type to store the functor for later use.
Can anyone point me in the right direction here?
|
template<class MyFunctor> MyMethod(MyFunctor f) {
boost::function<void()> g = f;
g();
}
The type you pass to boost::function is the function type. For example, int(bool, char) is the type of a function returning int and taking a bool and a char. That said, if you want to construct the shared_ptr right away, you don't need to store the functor somewhere (boost::function requires the new operator for that, even though for very small functors, it will use special tricks to only use stack allocation (small buffer optimization)):
template<class MyFunctor> MyMethod(MyFunctor f) {
boost::shared_ptr<T> ptr(new T, f);
}
boost::function is part of tr1 and will be part of the next official C++ Standard. Example:
struct Manager {
template<typename Deleter>
Manager(Deleter d)
:deleter(d) {
}
boost::shared_ptr<Resource> allocate() {
...
return boost::shared_ptr<Resource>(resource, deleter);
}
private:
boost::function<void(Resource *)> deleter;
};
|
474,521
| 477,992
|
What API to use for adding HTTP client support in an existing MFC app?
|
I have recently been given a task to add the ability to interact with Web Map Services to an existing MFC application and I am in need of a client-side HTTP API.
Based on my research, the leading candidates seem to be CAtlHttpClient and WinHTTP. I was curious to see if anyone had experiences they could share or opinions on which would be the better way to go (or suggestions for something else entirely).
At first glance, CAtlHttpClient seems to be a bit higher level and easier to use. However, in my research it seemed that any time people had a problem with not being able to do something with it, the answer was "use WinHTTP".
Result
I wound up using WinHTTP because WinInet displays dialog boxes and our application is usable through a COM API. I avoided Ultimate TCP/IP because I work for a large company and getting third party software approved for use in a product is a complete nightmare.
|
The simplest one is the WinInet MFC wrappers: CInternetSession and friends.
WinHTTP, although a different API, is built on the same model as WinInet yet provides better HTTP support (no FTP though but you probably don't care). Whether you need the extra goodies provided by WinHTTP should be examined.
A down side of WinHTTP is that ATL/MFC don't provide wrappers for it, as opposed to WinInet.
And as Rob mentioned, UltimateTCP is a excellent alternative. One of its advantages is that it's a library: you link the code into your application, thereby eliminating DLL hell potential problems. Also, it comes with full source code which might be convenient if you run into a limitation of the implementation.
Make your pick!
|
474,840
| 474,855
|
boost vs ACE C++ cross platform performance comparison?
|
I am involved in a venture that will port some communications, parsing, data handling functionality from Win32 to Linux and both will be supported. The problem domain is very sensitive to throughput and performance.
I have very little experience with performance characteristics of boost and ACE. Specifically we want to understand which library provides the best performance for threading.
Can anyone provide some data -- documented or word-of-mouth or perhaps some links -- about the relative performance between the two?
EDIT
Thanks all. Confirmed our initial thoughts - we'll most likely choose boost for system level cross-platform stuff.
|
Neither library should really have any overhead compared to using native OS threading facilities. You should be looking at which API is cleaner. In my opinion the boost thread API is significantly easier to use.
ACE tends to be more "classic OO", while boost tends to draw from the design of the C++ standard library. For example, launching a thread in ACE requires creating a new class derived from ACE_Task, and overriding the virtual svc() function which is called when your thread runs. In boost, you create a thread and run whatever function you want, which is significantly less invasive.
|
474,867
| 474,921
|
Counting the number of methods defined in a C++ header
|
Is there a tool to count the number of methods defined in a header? This seems like something that people would want to do from time to time, but I've never heard of such a utility. I could roll my own (and it'd be quite easy to come up with something that works for me in this particular case), but I thought I'd try stackoverflow first :)
Thanks,
Yi
|
Try this:
ctags --c++-kinds=f -x myfile.h
To list all functions in the file myfile.h . To count the number of functions in deque.tcc:
$ ctags --c++-kinds=f --language-force=c++ -x deque.tcc | wc -l
24
|
475,301
| 475,342
|
Tools for automatically generating unit tests for C++?
|
We have a large amount of legacy C++ code in shared libraries that are used on dozens of products. Ignoring the pros and cons of automatically generating tests (that's a discussion for another day), does anyone have any recommendations for a tool that would analyse the source and generate a set of tests to exercise that code?
Ideally it would be a Windows tool, Linux might be okay if absolutely necessary.
|
I've heard Parasoft mentioned a few times. I've never used their products, but the article "Change Software Without Fear" (written by one of their employees) covers automatic test generation ("behavioral regression testing," they call it) in a non-salesy fashion and touches briefly on their software.
|
475,570
| 475,601
|
Shared Library Discovery
|
I am using C++ on Linux. I want to dynamically bind a collection of unknown shared libraries. I need my code to detect all the public functions exposed by the shared library and the string names of those functions. How do I accomplish this task?
|
AFAIK, there is no glibc function to enumerate all the public interface functions for a .so file. You can refer to libelf to read all symbols from a dynamic file. Libelf is here http://www.mr511.de/software/. After you find a symbol, you can use dlopen and dlsym to load it.
|
475,619
| 475,695
|
C++0x implementation guesstimates?
|
The C++0x standard is on its way to being complete. Until now, I've dabbled in C++, but avoided learning it thoroughly because it seems like it's missing a lot of modern features that I've been spoiled by in other languages. However, I'd be very interested in C++0x, which addresses a lot of my complaints. Any guesstimates, after the standard is ratified, as to how long it will take for major compiler vendors to provide reasonably complete, production-quality implementations? Will it happen soon enough to reverse the decline in C++'s popularity, or is it too little, too late? Do you believe that C++0x will become "the C++" within a few years, or do you believe that most people will stick to the earlier standard in practice and C++0x will be somewhat of a bastard stepchild, kind of like C99?
|
I see no reason why C++0x shouldn't be adopted. The C++ community is much more forward-looking than C. C was always meant to be a "portable assembler language", so people who use that aren't really super interested in fancy new features. C++ spans much wider, and I've yet to hear of a C++ programmer who wasn't looking forward to 0x. (It's also my impression that the C++ community is much "stricter", and really don't want to move outside the standard into undefined behavior, which implies you choose either C++03 or C++0X rather than a half-implemented hybrid. C programmers tend to be much more relaxed about that, and seem happy to use C89 with just a couple of C99 features and headers mixed in)
However, it'll take a few years before Microsoft catches up, at least. Visual Studio 2010 will support a small handful of C++0x features (lambdas, decltype and a couple of others), but the vast majority will not be supported. We'll have to wait for VS2012 or whatever the next version ends up being, to have somewhat complete support.
With GCC/G++, the situation is a lot better, since most of the standard has been implemented there already (the standard committee doesn't like adopting features that haven't been implemented and tested in a real compiler, and a GCC fork is often used for that)
But it'll probably still take some time to get that stable and production-ready.
About C++'s "decline in popularity", I don't really see it. I don't think C++ has declined significantly in popularity for the last years. RAD developers have already jumped ship, of course, to .NET, Python or other languages or platforms. But where C++ is used today, there aren't many viable alternatives, and no reason why it should decline in popularity.
|
475,824
| 475,831
|
static_cast<int>(foo) vs. (int)foo
|
Could somebody please elaborate on the differences?
|
The difference is that (int)foo can mean half a dozen different things.
It might be a static_cast (convert between statically known types), it might be a const_cast (adding or removing const-ness), or it might be a reinterpret_cast (converting between pointer types)
The compiler tries each of them until it finds one that works. Which means that it may not always pick the one you expect, so it can become a subtle source of bugs.
Further, static_cast is a lot easier to search for or do search/replace on.
|
475,850
| 475,951
|
Converting UTF-8 to WIN1252 using C++Builder 5
|
I have to import some UTF-8 encoded text-file into my C++Builder 5 program.
Are there any components or code samples to accomplish that?
|
You are best off reading all the other questions on SO that are tagged unicode and c++. For starters you should probably look at this one and see whether library in the accepted answer (UTF8-CPP) works for you.
I would however first think about what you're trying to achieve, as there is no way you can just import UTF-8-encoded strings into "Ansi" (what ever you mean by that, maybe something like ISO8859_1 or WIN1252 encoding?).
|
475,853
| 476,014
|
Can I use CreateFile, but force the handle into a std::ofstream?
|
Is there any way to take advantage of the file creation flags in the Win32 API such as FILE_FLAG_DELETE_ON_CLOSE or FILE_FLAG_WRITE_THROUGH as described here http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx , but then force that handle into a std::ofstream?
The interface to ofstream is obviously platform independent; I'd like to force some platform dependent settings in 'under the hood' as it were.
|
It is possible to attach a C++ std::ofstream to a Windows file handle. The following code works in VS2008:
HANDLE file_handle = CreateFile(
file_name, GENERIC_WRITE,
0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle != INVALID_HANDLE_VALUE) {
int file_descriptor = _open_osfhandle((intptr_t)file_handle, 0);
if (file_descriptor != -1) {
FILE* file = _fdopen(file_descriptor, "w");
if (file != NULL) {
std::ofstream stream(file);
stream << "Hello World\n";
// Closes stream, file, file_descriptor, and file_handle.
stream.close();
file = NULL;
file_descriptor = -1;
file_handle = INVALID_HANDLE_VALUE;
}
}
This works with FILE_FLAG_DELETE_ON_CLOSE, but FILE_FLAG_WRITE_THROUGH may not have the desired effect, as data will be buffered by the std::ofstream object, and not be written directly to disk. Any data in the buffer will be flushed to the OS when stream.close() is called, however.
|
475,888
| 475,927
|
Will this lead to a memory leak in C++?
|
I have a C++ memory management doubt, that's (obviously) related to references and pointers. Suppose I have a class Class with a method my_method:
OtherClass& Class::my_method( ... ) {
OtherClass* other_object = new OtherClass( ... );
return *other_object;
}
Meanwhile in a nearby piece of code:
{
Class m( ... );
OtherClass n;
n = m.my_method( ... );
}
So, I know that there's a general rule about pointers (~ "anything new-ed, must be delete-d") to avoid memory leaks. But basicly I'm taking a reference to my heap-allocated object, so when n goes out of scope, shouldn't the destructor of OtherClass be called thus freeing the memory previously pointed by other_object?
So in the end the real question is: will this lead to a memory leak?
Thanks.
|
It's fairly obvious that you want to return a new object to the caller that you do not need to keep any reference to. For this purpose, the simplest thing to do is to return the object by value.
OtherClass Class::my_method( ... ) {
return OtherClass( ... );
}
Then in the calling code you can construct the new object like this.
{
Class m( ... );
OtherClass n( m.mymethod( ... ) );
}
This avoids any worries about returning reference to temporaries or requiring the client to manager deletion of a returned pointer. Note, that this does require your object to be copyable, but it is a legal and commonly implemented optimization for the copy to be avoided when returning by value.
You would only need to consider a shared pointer or similar if you need shared ownership or for the object to have a lifetime outside the scope of the calling function. In this latter case you can leave this decision up to the client and still return by value.
E.g.
{
Class m( ... );
// Trust me I know what I'm doing, I'll delete this object later...
OtherClass* n = new OtherClass( m.mymethod( ... ) );
}
|
475,973
| 475,977
|
How to load digital signals from a USB port into memory?
|
My friend is working on a project in which he needs to get some digital signals into a computer to display/manipulate them.
So I advised him to insert those signals into a USB port due to it's popularity (because the device (which outputs the signals) and the program used for display and manipulation should both be designed for real world usage and might be sold in the market)
The targeted platform is Windows primarily but it would be better if the software was cross-platform.
And my friend has knowledge in C++, and wouldn't mind learning C as well.
Where should he start, and what are the steps to get the signals into memory?
Many Thanks
|
There is a great article here: USB hardware/software integration that describes the process in full.
|
476,043
| 476,048
|
Is there a way to call an unmanaged (not COM) dll from C# application?
|
Is there a way to use (reference) a DLL written in an unmanaged C++ (not a COM library) in my C# application?
When I try to reference it from within Visual Studio, I get 'not a COM object' error message.
Maybe there is some kind of translator\router that would COMify my DLL reference?
I have no clue how COM and COM interop work, since I started programming when this was already unnecessary for me.
Thank you.
|
You need to use the DllImport attribute. Here's an example for the Win32 PostMessage function:
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PostMessage(IntPtr handle, int message, IntPtr wparam, IntPtr lparam);
|
476,212
| 476,225
|
What is the precision of long double in C++?
|
Does anyone know how to find out the precision of long double on a specific platform? I appear to be losing precision after 17 decimal digits, which is the same as when I just use double. I would expect to get more, since double is represented with 8 bytes on my platform, while long double is 12 bytes.
Before you ask, this is for Project Euler, so yes I do need more than 17 digits. :)
EDIT: Thanks for the quick replies. I just confirmed that I can only get 18 decimal digits by using long double on my system.
|
You can find out with std::numeric_limits:
#include <iostream> // std::cout
#include <limits> // std::numeric_limits
int main(){
std::cout << std::numeric_limits<long double>::digits10 << std::endl;
}
|
476,272
| 476,279
|
How to properly overload the << operator for an ostream?
|
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2
) however I have the same problem on a Ubuntu system with the same g++.
Here is the relevant part of my matrix class:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
}
}
And the "implementation":
using namespace Math;
std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {
[...]
}
This is the error given by the compiler:
matrix.cpp:459: error: 'std::ostream&
Math::Matrix::operator<<(std::ostream&,
const Math::Matrix&)' must take
exactly one argument
I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)
|
You have declared your function as friend. It's not a member of the class. You should remove Matrix:: from the implementation. friend means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix class which is wrong.
|
476,461
| 476,465
|
Programming style of method declaration of get/set method variables in C++?
|
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp.
|
For me it depends on who's going to be using the .h file. If it's a file largely internal to a module, then I tend to put the tiny methods in the header. If it's a more external header file that presents a more fixed API, then I'll put everything in the .cpp files. In this case, I'll often use the PIMPL Idiom for a full compilation firewall.
The trade-offs I see with putting them in the headers are:
Less typing
Easier inlining for the compiler (although compilers can sometimes do inlining between multiple translation units now anyway.)
More compilation dependencies
|
476,488
| 476,507
|
How to use std::foreach with parameters/modification
|
I've found myself writing
for(int i=0;i<myvec.size();i++)
myvec[i]->DoWhatever(param);
a lot, and I'd like to compress this into a foreach statement, but I'm not sure how to get param in there without going super-verbose. I've also got things like
for(int i=0;i<myvec.size();i++)
if(myvec[i]->IsOK())
myvec[i]->DoWhatever(param);
and I'd like to rewrite that guy too. Any thoughts?
Oh, also, for various reasons, I don't want to use boost.
|
#include <vector>
#include <algorithm>
#include <functional>
class X
{
public:
void doWhat(int x) {}
bool IsOK() const {return true;}
};
class CallWhatIfOk
{
public:
CallWhatIfOk(int p): param(p) {}
void operator()(X& x) const
{ if (x.IsOK()) {x.doWhat(param);}}
private:
int param;
};
int main()
{
std::vector<X> myVec;
std::for_each( myVec.begin(),
myVec.end(),
std::bind2nd(std::mem_fun_ref(&X::doWhat),4)
);
std::for_each( myVec.begin(),
myVec.end(),
CallWhatIfOk(4)
);
}
|
476,800
| 476,834
|
Comparing two integers without any comparison
|
Is it possible to find the greatest of two integers without any comparison? I found some solutions:
if(!(a/b)) // if a is less than b then division result will be zero.
{
cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now. check whether they are equal.
{
cout << "a and b are equal";
}
else
cout << "a is greater than b";
But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.
|
Subtract them and check the sign using nasty bit twiddling hacks
http://graphics.stanford.edu/~seander/bithacks.html
Don't do this in production code if the other programmers know where you live.
|
477,225
| 477,252
|
Is std::ifstream significantly slower than FILE?
|
I've been informed that my library is slower than it should be, on the order of 30+ times too slow parsing a particular file (text file, size 326 kb). The user suggested that it may be that I'm using std::ifstream (presumably instead of FILE).
I'd rather not blindly rewrite, so I thought I'd check here first, since my guess would be the bottleneck is elsewhere. I'm reading character by character, so the only functions I'm using are get(), peek(), and tellg()/seekg().
Update:
I profiled, and got confusing output - gprof didn't appear to think that it took so long. I rewrote the program to read the entire file into a buffer first, and it sped up by about 100x. I think the problem may have been the tellg()/seekg() that took a long time, but gprof may have been unable to see that for some reason. In any case, ifstream does not appear to buffer the entire file, even for this size.
|
I don't think that'd make a difference. Especially if you're reading char by char, the overhead of I/O is likely to completely dominate anything else.
Why do you read single bytes at a time? You know how extremely inefficient it is?
On a 326kb file, the fastest solution will most likely be to just read it into memory at once.
The difference between std::ifstream and the C equivalents, is basically a virtual function call or two. It may make a difference if executed a few tens of million times per second, otherwise, not reall. file I/O is generally so slow that the API used to access it doesn't really matter. What matters far more is the read/write pattern. Lots of seeks are bad, sequential reads/writes good.
|
477,331
| 477,353
|
How to use the "removed" elements after std::remove_if
|
Say we've got:
struct IsEven {
bool operator() (int i) { return i % 2 == 0; }
};
Then:
vector<int> V; // fill with ints
vector<int>::iterator new_end = remove_if(V.begin(), V.end(), IsEven());
V.erase(new_end, V.end());
works fine (it leaves V with only the odd integers). But it seems that the elements from new_end to V.end() are not the even integers that we're deleting. For example, if v starts out as 1 4 2 8 5 7, then I'm getting 8 5 7 for those elements (although after the erase call, the vector indeed has 1 5 7 left).
Apparently, (according to http://www.sgi.com/tech/stl/remove_if.html)
The iterators in the range [new_last, last) are all still dereferenceable,
but the elements that they point to are unspecified.
First of all, WTF? And second, how do I get around this without essentially reimplementing remove_if?
|
It sounds like you want to use partition() to partition the vector into groups of odd values at the start and even values at the end. partition() will return an iterator to the first element of the second grouping.
As for the WTF, I'm not sure why you would expect a remove operation to preserve the elements you want to remove by copying them (that's extra work) to the end of the container.
Most people consider the WTF in remove() (and it's cousins) to be the fact that the size of the vector is not reduced and you have to call erase() to actually delete undesired elements after the remove operation.
|
477,427
| 477,436
|
c++ ifstream, detect if letter or EOLine?
|
I have this function to read in all ints from the file.
The problem is when i read letters i trigger a new line and i always seek by 1 and not to the end of line. How can i write this function better?
int v;
while (!in.eof())
{
while (in >> v)
cout << v << " ";
cout << endl;
if (in.eof())
break;
in.clear();
in.seekg(1, ios::cur);
int a;
a=0;
}
|
If your file consists of just ints separated by whitespace (including) newlines then this should be sufficient.
while( in >> v )
{
// do something with v
}
After the file, if in.fail() is false and in.eof() is true, then you reached the end of the file without a formatting error. Otherwise an error reading an int occurred.
If you receive invalid input and want to recover from that then you need to work out how you want to recover. If you want to skip until the end of the line and start parsing again, you can use something like this.
in.clear();
in.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
|
477,452
| 477,481
|
Coding practice: return by value or by reference in Matrix multiplication?
|
I'm writing this question with reference to this one which I wrote yesterday. After a little documentation, it seems clear to me that what I wanted to do (and what I believed to be possible) is nearly impossible if not impossible at all. There are several ways to implement it, and since I'm not an experienced programmer, I ask you which choice would you take. I explain again my problem, but now I have some solutions to explore.
What I need
I have a Matrix class, and I want to implement multiplication between matrices so that the class usage is very intuitive:
Matrix a(5,2);
a(4,1) = 6 ;
a(3,1) = 9.4 ;
... // And so on ...
Matrix b(2,9);
b(0,2) = 3;
... // And so on ...
// After a while
Matrix i = a * b;
What I had yesterday
At the moment I overloaded the two operators operator* and operator= and until yesterday night the were defined in this way:
Matrix& operator*(Matrix& m);
Matrix& operator=(Matrix& m);
The operator* instantiates a new Matrix object (Matrix return = new Matrix(...)) on the heap, set the values and then just:
return *result;
What I have today
After the discussion I decided to implement it in a "different way" to avoid the user to be bothered bother by pointers of any type and to keep the usage unchanged. The "different way" is to pass the returning value of operator* by value:
Matrix operator*(Matrix& m);
Matrix& operator=(Matrix& m);
The operator* instantiates return on the stack, set the values and then return the object.
There is a problem with this approach: it doesn't work. The operator= expects a Matrix& and operator* returns a Matrix. Moreover this approach doesn't look so good to me for another reason: I'm dealing with matrices, that can be very large and the aims of this library were to be 1) good enough for my project 2) fast, so probably passing by value should not be an option.
Which solutions I have explored
Well, following the suggestions in the previous discussion I read some stuff about smart pointers, they look great but I can't still figure out how to solve my problem with them. They deal with memory freeing and pointer copying, but I'm basicly using references, so they don't look the right choice for me. But I may be wrong.
Maybe the only solution is to pass by value, maybe I can't get both efficiency and a good interface. But again, you're the expert, and I would like to know your opinion.
|
The problem you are having is that the expression a * b creates a temporary object, and in C++, a temporary is not allowed to bind to a non-constant reference, which is what your Matrix& operator=(Matrix& m) takes. If you change it to:
Matrix& operator=(Matrix const& m);
The code should now compile. As well as the obvious benefit of producing compilable code :), adding the const also communicates to your callers that you will not be modifying the argument m, which may be helpful information.
You should also do the same for your operator*():
Matrix operator*(Matrix const& m) const;
[EDIT: The additional const at the end indicates that the method promises not to alter *this, the object on the left-hand side of the multiplication, either. This is necessary to cope with expressions such as a * b * c -- the subexpression a * b creates a temporary and won't bind without the const at the end. Thanks to Greg Rogers for pointing this out in the comments.]
P.S. The reason why C++ does not allow a temporary to bind to a non-constant reference is because temporaries exist (as the name suggests) for only a very short time, and in most cases, it would be a mistake to attempt to modify them.
|
477,461
| 477,466
|
When building a DLL file, does the generated LIB file contain the DLL name?
|
In Visual C++ , when I build a dll , the output files are .dll and .lib.
Is the name of the dll built into the .lib file .
The reasson I ask this question is : When I built my exe by importing this dll and run the exe , the exe tries to locate the dll to load it in the process address space .
As we just specify the library name (.lib file) in the project properties , how does the exe get to know the name of the dll .
Note : I dumpbin libary file (.lib) and saw that it does not contain the name of the dll .
|
The LIB file is turned into an import table in the EXE. This does contain the name of the DLL.
You can see this if you run dumpbin /all MyDLL.lib. Note that dumpbin MyDll.lib by itself doesn't show anything useful: you should use /all.
This shows all of the sections defined in the .LIB file. You can ignore any .debug sections, because they wouldn't be present in a Release build. In the .LIB file, there are a collection of .idata sections. In the DLL project that I just built, the LIB file contains a .idata$4 section which defines the symbols to be put in the EXE's import table, including the DLL name:
Archive member name at 83E: MyDll.dll/
497C3B9F time/date Sun Jan 25 10:14:55 2009
uid
gid
0 mode
2E size
correct header end
Version : 0
Machine : 14C (x86)
TimeDateStamp: 497C3B9F Sun Jan 25 10:14:55 2009
SizeOfData : 0000001A
DLL name : MyDll.dll
Symbol name : ?fnMyDll@@YAHXZ (int __cdecl fnMyDll(void))
Type : code
Name type : name
Hint : 2
Name : ?fnMyDll@@YAHXZ
|
477,503
| 477,517
|
Mounting folder as a drive in vista
|
Hi I am trying to mount as a drive in vista I am using the following code from msdn example,
BOOL bFlag;
TCHAR Buf[BUFSIZE]; // temporary buffer for volume name
if( argc != 3 )
{
_tprintf( TEXT("Usage: %s <mount_point> <volume>\n"), argv[0] );
_tprintf( TEXT("For example, \"%s c:\\mnt\\fdrive\\ f:\\\"\n"), argv[0]);
return( -1 );
}
// We should do some error checking on the inputs. Make sure
// there are colons and backslashes in the right places, etc.
bFlag = GetVolumeNameForVolumeMountPoint(
argv[2], // input volume mount point or directory
Buf, // output volume name buffer
BUFSIZE // size of volume name buffer
);
if (bFlag != TRUE)
{
_tprintf( TEXT("Retrieving volume name for %s failed.\n"), argv[2] );
return (-2);
}
_tprintf( TEXT("Volume name of %s is %s\n"), argv[2], Buf );
bFlag = SetVolumeMountPoint(
argv[1], // mount point
Buf // volume to be mounted
);
if (!bFlag)
_tprintf (TEXT("Attempt to mount %s at %s failed.\n"), argv[2], argv[1]);
return (bFlag);
It always gives an error of parameter is incorrect , I also tried definedosdevice at first then get the name, It also didn't work. Any idea how to make it work?
|
SetVolumeMountPoint is for mounting a volume on a drive letter or in a folder. It does not allow you to mount a folder on a drive letter. This is the opposite of what you want.
To make a folder available as a drive letter, you want to do the equivalent of the SUBST utility. This uses DefineDosDevice, something like this:
if (!DefineDosDevice(0, _T("Q:"), _T("C:\\Temp")))
_ftprintf(stderr, _T("DefineDosDevice failed: %d\n"), GetLastError());
If you want to make this persistent, I think that you'll need to write a Windows service that does it at boot time. I wrote one about 10 years ago.
|
477,525
| 477,558
|
Expression Evaluation in C++
|
I'm writing some excel-like C++ console app for homework.
My app should be able to accept formulas for it's cells, for example it should evaluate something like this:
Sum(tablename\fieldname[recordnumber], fieldname[recordnumber], ...)
tablename\fieldname[recordnumber] points to a cell in another table,
fieldname[recordnumber] points to a cell in current table
or
Sin(fieldname[recordnumber])
or
anotherfieldname[recordnumber]
or
"10" // (simply a number)
something like that.
functions are Sum, Ave, Sin, Cos, Tan, Cot, Mul, Div, Pow, Log (10), Ln, Mod
It's pathetic, I know, but it's my homework :'(
So does anyone know a trick to evaluate something like this?
|
Ok, nice homework question by the way.
It really depends on how heavy you want this to be. You can create a full expression parser (which is fun but also time consuming).
In order to do that, you need to describe the full grammar and write a frontend (have a look at lex and yacc or flexx and bison.
But as I see your question you can limit yourself to three subcases:
a simple value
a lookup (possibly to an other table)
a function which inputs are lookups
I think a little OO design can helps you out here.
I'm not sure if you have to deal with real time refresh and circular dependency checks. Else they can be tricky too.
|
477,787
| 477,836
|
C++, windows->linux porting, mapfile problem
|
I'm porting a small C++ console application from windows to linux, GCC 4.3.2. When compiling I get strange error that I'm unable to solve.
Labels.cpp: In function ‘void DumpSymbols()’:
Labels.cpp:68: error: invalid conversion from ‘int’ to ‘std::_Ios_Openmode’
Labels.cpp:68: error: initializing argument 2 of ‘std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]’
Labels.cpp:
#include <string>
#include <fstream>
#include <iostream>
#include "stdafx.h"
using namespace std;
#include "Opcodes.h"
#include "Labels.h"
Label LABELS[1024];
int labelcounter = 0;
int OffsetCounter = 0;
void AddLabel(string name, int line)
{
LABELS[labelcounter].name = name;
LABELS[labelcounter].line = line;
LABELS[labelcounter].offset = OffsetCounter;
printf("Adding label: %s[0x%X]\n", name.c_str(), OffsetCounter);
labelcounter++;
}
bool IsLabel(string name)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(name) == 0)
{
return true;
}
}
return false;
}
int GetOffset(string lbl)
{
for(int i=0;i<labelcounter;i++)
{
if (LABELS[i].name.compare(lbl) == 0)
{
printf("Refers to label '%s':0x%X\n", lbl.c_str(), LABELS[i].offset);
return LABELS[i].offset;
}
}
return -1;
}
void DumpSymbols()
{
ofstream mapfile("symbols.map", ios::out|ios::beg); //this line causes error
//mapfile.write(
char numbuf1[32];
itoa(labelcounter, numbuf1, 10);
mapfile.write((string(numbuf1) + "\n").c_str(), strlen(numbuf1)+1);
for(int i=0;i<labelcounter;i++)
{
string dump;
char numbuf[32];
itoa(LABELS[i].offset, numbuf, 10);
dump = string(LABELS[i].name) + "\t" + string(numbuf) + "\n";
mapfile.write(dump.c_str(), strlen(dump.c_str()));
}
}
stdafx.h:
#pragma once
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cstdlib>
Thanks.
|
Just remove "|ios::beg":
ofstream mapfile("symbols.map", ios::out);
It's type is ios_base::seekdir, which is not an opening mode; it's for seeking to a position. You'll automatically be at the beginning anyway.
|
477,829
| 477,868
|
cannot call base class protected functions?
|
I cant call protected function in my base class. Why? It looks something like this:
class B : B2
{
public:
virtual f1(B*)=0;
protected:
virtual f2(B*) { codehere(); }
}
class D : public B
{
public:
virtual f1(B*b) { return f2(b); }
protected:
virtual f2(B*b) { return b->f2(this); }
}
In msvc I get the error error C2248: 'name::class::f2' : cannot access protected member declared in class 'name::class'
In gcc I get error: 'virtual int name::class::f2()' is protected.
Why is that? I thought the point of protected members is for derived classes to call.
|
Protected member functions can only be called inside the base class or in its derived class. You cannot call them outside your class. Outside calling means calling a member function of a class-typed variable.
So
virtual f1(B*b) { return f2(b); }
is ok, because f2 operates on the class itself. (called inside)
But
virtual f2(B*b) { return b->f2(this); }
won't compile, because f2 operates on b not the class D itself. (called outside) It's illegal.
To fix it B::f2 should be public.
|
477,885
| 477,889
|
Visual C++ express 2008: Why does it places megs of null bytes at the end of the release executable?
|
Recently I have discovered that my release executable (made with msvc++ express 2008) becomes very large. As I examine the executable with a hex viewer I saw that only the first 300k bytes contains useful data the remaining bytes are only zeros - 6 megs of zero bytes.
The debug built exe has 1MB size, but the release is 6.5MB.
Why does MSVC++ express do that useless thing? How can I fix it?
|
Did you define large arrays at file-scope in your program? That might be one reason. You can use the dumpbin program to see how much space each section in the exe file takes, that should give you a clue to the "why".
|
477,945
| 477,996
|
POCO C++ libraries on CDT
|
I am working with CDT (C/C++ for eclipse) on windows, and I need to start using POCO C++ libraries
The current package distribution for POCO requires MS Visual Studio 7/8/9 for compiling the libs.
Does anyone know a solution for compiling in a CDT environment on windows? I am using MinGW for compile/build tools.
|
It is possible to use POCO with MinGW - some folks already do this successfully. I would first try to get going with MinGW alone, and when this works, integrate it into Eclipse (which shouldn't be too hard.).
There are some patches and bug reports in POCO's tracker on SourceForge. Looking at them will certainly help (https://sourceforge.net/tracker/?group_id=132964).
|
478,037
| 478,041
|
How can I make the program I wrote with QT4 execute when I launch it not from IDE?
|
When I run the program from IDE (VS2008) it works perfectly. When I want to launch it from Windows Commander it doesn't work because it needs DLL that wasn't found.
Used both debug and release builds.
|
Make sure the Qt DLL's are in your PATH. Two simple solutions are:
Copy Qt's DLL's to your EXE's directory.
Copy Qt's DLL's to %WINDOWS%\System32 (e.g. C:\WINDOWS\System32) (possibly unsafe, especially if you install another versions of Qt system-wide. Also, requires administrative privilages).
|
478,075
| 478,088
|
Creating files in C++
|
I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.
Can anyone help me?
|
One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:
ofstream reference
For completeness, here's some example code:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.
|
478,165
| 478,271
|
How to create an efficient 2D grid in C++?
|
I want to create a really easy to use 2D Grid. Each cell in the grid needs to be able to store a load of data. Ideally I would like to be able to traverse through the grid one cell at a time, as well as obtain the immediate neighbours of any of the grid cells.
My first thought was to store a vector of pointers to a Cell's neighbours (4 in total), then create convenience functions for leftNeighbour, rightNeighbour, etc. Connecting up the grid after initialization.
The std::vector is supposed to be a dynamically resizeable array, so this strikes me as rather unnecessary if I'm only going to hard-code the positions of the pointers (0 == left, 1 == right, etc). However, it does allow a nicer way of iterating through the neighbours of a cell. The other thing I have to consider is if the cell is on a border with the edge of the grid (whether to test for this or just implicitly extend the grid by one cell so that this will never happen).
Can anyone suggest a better alternative, or does this sound like a reasonable design?
Thanks, Dan
|
If you want a four-direction iterator, make your own:
template<typename T, int width, int height>
class Grid {
public:
T data[width * height];
iterator begin() {
return iterator(data);
}
iterator end() {
return iterator(data + width * height);
}
class iterator {
public:
iterator(const iterator &other) :
ptr(other.ptr)
{
}
iterator &left() const {
return iterator(ptr - 1);
}
iterator &right() const {
return iterator(ptr + 1);
}
iterator &up() const {
return iterator(ptr - width);
}
iterator &down() const {
return iterator(ptr + width);
}
iterator &operator++() {
++ptr;
return *this;
}
iterator &operator--() {
--ptr;
return *this;
}
iterator operator++(int) {
++*this;
return iterator(ptr + 1);
}
iterator operator--(int) {
--*this;
return iterator(ptr - 1);
}
T operator*() const {
return *ptr;
}
private:
iterator();
iterator(T *ptr_) :
ptr(ptr_)
{
}
T *ptr;
friend class Grid;
};
};
You may want to detect if you hit the edge of your grid, among other things, and that would have to be implemented.
|
478,298
| 478,314
|
How do I write a C++ program that will easily compile in Linux and Windows?
|
I am making a C++ program.
One of my biggest annoyances with C++ is its supposed platform independence.
You all probably know that it is pretty much impossible to compile a Linux C++ program in Windows and a Windows one to Linux without a deluge of cryptic errors and platform specific include files.
Of course you can always switch to some emulation like Cygwin and wine, but I ask you, is there really no other way?
|
The language itself is cross-platform but most libraries are not, but there are three things that you should keep in mind if you want to go completely cross-platform when programming in C++.
Firstly, you need to start using some kind of cross-platform build system, like SCons. Secondly, you need to make sure that all of the libraries that you are using are built to be cross-platform.
And a minor third point, I would recommend using a compiler that exists on all of your target platforms, gcc comes in mind here (C++ is a rather complex beast and all compilers have their own specific quirks).
I have some further suggestions regarding graphical user interfaces for you. There are several of these available to use, the three most notable are:
GTK+
QT
wxWidgets
GTK+ and QT are two API's that come with their own widget sets (buttons, lists, etc.), whilst wxWidgets is more of a wrapper API to the currently running platforms native widget set. This means that the two former might look a bit differently compared to the rest of the system whilst the latter one will look just like a native program.
And if you're into games programming there are equally many API's to choose from, all of them cross-platform as well. The two most fully featured that I know of are:
SDL
SFML
Both of which contains everything from graphics to input and audio routines, either through plugins or built-in.
Also, if you feel that the standard library in C++ is a bit lacking, check out Boost for some general purpose cross-platform sweetness.
Good Luck.
|
478,482
| 478,550
|
Express the usage of C++ arguments through method interfaces
|
Is there a common way to express the usage of arguments in C++? I want to implicitly tell the consumers of my class how the arguments they pass will be used by the class.
Examples:
I own your argument (will clean it up)
I will hold a reference to your argument during my lifetime (so you should NOT delete it while I'm stile alive)
I will use your argument only during construction and won't hold a reference
Is there a common way to express these things simply using the method declaration? I think in the first case a std::auto_ptr would make sense. In the second case I usually take a pointer to avoid someone passing a value from the stack which would invalidate my reference quickly, or alternatively a shared_ptr. In the third case I take a reference to allow values from the stack.
How do you deal with this? Also is it necessary to rely on smart pointers here, or can one express such things simply by using naked references and pointers somehow?
|
Our team has similar coding conventions to the ones you suggest:
1 - auto_ptr argument means that the class will take control of memory management for the object. (We don't use this much.)
2 - shared_ptr means that the class will probably use the argument for an extended period of time, and in particular may store off its own shared_ptr to the object.
3 - Plain reference means that the argument will only be used for the duration of the call.
We treat this as a coding standard. It isn't something we document for each and every call.
|
478,668
| 479,127
|
Boost Serialization using polymorphic archives
|
I am working on a client-server application that uses boost::serialization library for it's serialization needs.
I need to serialize and deserialize polymorphic objects that does not seem to work. The documentation does say that it is supported but none of the related examples demonstrate what I'm trying to do here. So, I am not very sure. My question is can serialize/deserialize polymorphic objects using boost? If yes, what am I doing wrong here?
Thanks!
code:
using namespace std;
class base {
public:
int data1;
friend class boost::serialization::access;
void serialize(boost::archive::polymorphic_iarchive & ar,
const unsigned int file_version) {
ar & data1;
}
void serialize(boost::archive::polymorphic_oarchive & ar,
const unsigned int file_version){
ar & data1;
}
public:
base() {};
base(int _d) : data1(_d) {}
virtual void foo() const {std::cout << "base" << std::endl;}
};
class derived : public base {
public:
int data2;
friend class boost::serialization::access;
void serialize(boost::archive::polymorphic_iarchive & ar,
const unsigned int file_version) {
ar & boost::serialization::base_object<base>(*this) & data2;
}
void serialize(boost::archive::polymorphic_oarchive & ar,
const unsigned int file_version){
ar & boost::serialization::base_object<base>(*this) & data2;
}
public:
derived() {};
derived(int _b, int _d) : base(_b), data2(_d) {}
virtual void foo() const {std::cout << "derived" << std::endl;}
};
int main(int argc, char *argv[]) {
// client
const base *b1 = new derived(1, 2);
std::ostringstream oss;
boost::archive::polymorphic_text_oarchive oa(oss);
oa << *b1;
// server
base *b2 = new derived(3, 4);
std::istringstream iss(oss.str());
boost::archive::polymorphic_text_iarchive ia(iss);
ia >> *b2;
// prints 1, ok
cout << b2->data1 << endl;
// prints 4, why wasn't the derived class data written?
cout << (dynamic_cast<derived*>(b2))->data2 << endl;
return 0;
}
|
Found a resolution. I had to export the derived class with the statement:
BOOST_CLASS_EXPORT(derived);
Posting something that works with some corrections.
using namespace std;
class base {
public:
int data1;
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive & ar, const unsigned int file_version) {
ar & data1;
}
public:
base() {};
base(int _d) : data1(_d) {}
virtual void foo() const {std::cout << "base" << std::endl;}
};
class derived : public base {
public:
int data2;
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive & ar, const unsigned int file_version) {
ar & boost::serialization::base_object<base>(*this);
ar & data2;
}
public:
derived() {};
derived(int _b, int _d) : base(_b), data2(_d) {}
virtual void foo() const {std::cout << "derived" << std::endl;}
};
BOOST_CLASS_EXPORT(derived);
int main(int argc, char *argv[]) {
// client
// Assign to base type
std::unique_ptr<const base> b1(new derived(1, 2));
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
oa & b1.get();
// server
// Retrieve derived type from base
std::unique_ptr<base> b2;
std::istringstream iss(oss.str());
boost::archive::text_iarchive ia(iss);
{
base *temp;
ia & temp;
b2.reset(temp);
}
cout << b2->data1 << endl;
cout << (dynamic_cast<derived*>(b2.get()))->data2 << endl;
return 0;
}
|
478,725
| 485,909
|
Why is the OO concept interface not represented by a keyword in C++?
|
Languages such as Java explicitly use the interface keyword to denote interfaces. Having used Java, the concept seems useful enough to me to justify a keyword to enforce the concept.
Of course one can use a pure virtual class and label it as an interface. However, this keyword seems to be so useful and differentiated from a pure virtual class as to be useful. Perhaps it is being included in C++ 0x?
|
The early OO features of C++ have long been neglected because it has since moved in a more interesting direction as a multi-paradigm language. The major focus for over a decade now has been templates and their implications, particularly in the standard library. Yes, programs would be more readable with an interface keyword. They would also be easier to maintain if there were override and new modifiers for methods that have the same name as base class methods (a la C#). But these are not interesting problems to modern C++ users, nor to those who contribute to the language design. The OO features are adequate, but not great, and are hardly used in the "newer" (post 1992) parts of the standard library, which in some ways serves as a guide to good style.
|
478,898
| 478,960
|
How do I execute a command and get the output of the command within C++ using POSIX?
|
I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for:
std::string result = system("./some_command");
I need to run an arbitrary command and get its output. I've looked at boost.org, but I have not found anything that will give me what I need.
|
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
Pre-C++11 version:
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
Replace popen and pclose with _popen and _pclose for Windows.
|
478,911
| 478,964
|
Silverlight and C++ or C++ to C# ongoing code conversion?
|
I am working on a drawing-based product where I want to produce versions for iPhone, desktop OS/X, Windows Tablets, Silveright-based browser, Windows Mobile, and Windows in that order of priority.
For GUI portability, the classic answer is to keep the core in C++ and use Cocoa/Objective-C or WPF/C# thin layers.
However, Silverlight complicates the choices.
I wouldn't have any problem migrating my code into C++/CLI and maintaining a dual code base (with some macros to fake the C++/CLI contextual keywords and some judicial search and replace for ^ and %).
From what I've been able to find so far, it seems unlikely that C++/CLI will be supported in Silverlight. That leaves me with the options:
Once-off migration of a v1.0 C++ source base into C# and ongoing parallel maintenance
Live porting with a tool (recommendations please!) from C++ to C# or vice-versa, which is sufficiently smooth to be part of a build process.
Architectural separation of the Silverlight version so the C++ logic remains on a server. I'm a bit uncomfortable about the performance implications.
Can anyone suggest alternatives, provide good news on C++/CLI in Silverlight or recommend porting tools? I'm sufficiently comfortable in either language to make C++ or C# my main language for the backend provided a port is reliable.
Edit:
Looking at the range of products offered by Tangible Software Solutions, their notes on the converters make it clear that converting C# to C++ is easier than the other way. That is as I expected - it raises interesting thoughts as to constraining my C++ style to be least-common-OO-denominator.
|
Architectural separation of the Silverlight version so the C++ logic remains on a server. I'm a bit uncomfortable about the performance implications.
I'd do this. The performance is probably not as bad as you imagine.
|
478,967
| 478,986
|
C++ Array Member of Constant Length (Initialisation of)
|
I have a class that contains an array. I want this array to be set at the length of a constant:
// Entities.h
class Entities
{
private:
const int maxLimit;
int objects[maxLimit];
int currentUsage;
public:
Entities();
bool addObject(int identifier);
void showStructure();
};
The main problem I'm having is with the constructor. I thought:
// Entities.cpp
Entities::Entities() : maxLimit(50)
{
currentUsage = 0;
cout << "Entities constructed with max of 50" << endl;
}
would have been sufficient...but not so. I don't know if I can use the initialiser list for array initialisation.
How can I initialise the objects array using the maxLimit const? I'm relatively new to classes in C++ but I have experience with Java. I'm mainly testing out this phenomenon of 'constness'.
|
The array must have a constant length. I mean a length that is the same for all objects of that class. That is because the compiler has to know the size of each object, and it must be the same for all objects of that particular class. So, the following would do it:
class Entities
{
private:
static const int maxLimit = 50;
int objects[maxLimit];
int currentUsage;
public:
Entities();
bool addObject(int identifier);
void showStructure();
};
And in the cpp file:
const int Entities::maxLimit;
I prefer to use an enumeration for that, because i won't have to define the static in the cpp file then:
class Entities
{
private:
enum { maxLimit = 50 };
int objects[maxLimit];
int currentUsage;
public:
Entities();
bool addObject(int identifier);
void showStructure();
};
If you want to have a per-object size of the array, then you can use a dynamic array. vector is such one:
class Entities
{
private:
const int maxLimit;
std::vector<int> objects;
int currentUsage;
public:
Entities();
bool addObject(int identifier);
void showStructure();
};
// Entities.cpp
Entities::Entities(int limit)
: maxLimit(limit), objects(limit), currentUsage(0)
{
cout << "Entities constructed with max of 50" << endl;
}
Best is to do as much initialization in the initialization list as possible.
|
479,080
| 479,256
|
trim is not part of the standard c/c++ library?
|
Is it me or are there no standard trim functions in the c or c++ library? is there any single function that acts as a trim? If not can anyone tell me Why trim is not part of the standard library? (i know trim is in boost)
My trim code is
std::string trim(const std::string &str)
{
size_t s = str.find_first_not_of(" \n\r\t");
size_t e = str.find_last_not_of (" \n\r\t");
if(( string::npos == s) || ( string::npos == e))
return "";
else
return str.substr(s, e-s+1);
}
test: cout << trim(" \n\r\r\n \r\n text here\nwith return \n\r\r\n \r\n ");
-edit-
i mostly wanted to know why it wasnt in the standard library, BobbyShaftoe answer is great. trim is not part of the standard c/c++ library?
|
The reason trim() isn't in the standard library is that when the last standard was made, they had to strike a balance between formalizing current behavior (adding nothing new, just stabilizing what already existed), and adding new functionality. In general, they preferred not to add a feature unless it either 1) would be impossible otherwise, or 2) there were significant drawbacks to using third-party libraries instead. Making too many changes would
break compatibility with existing code (which may have defined its own trim()
Add more work for compiler writers (who already had a huge amount of work ahead of them)
Make the language more complex to learn and use.
With trim(), there are no major interoperability issues. As long as your third-party trim() implementation takes a string and returns a string, we don't really care where it's defined. So it's not really necessary In the standard library. It can be easily supplied by other libraries.
By contrast, something like the string class or vector, are classes that the standard library must supply, because if you use a custom string class, only string operations from that library will work. With a standard library string, third-party libraries can target this common string definition, and everyone wins.
When the last standard came out, Herb Sutter wrote a post describing this very well here
Of course, it would be nice to have a trim() function, but they had bigger fish to fry. They had to standardize all the basics first. I don't think C++0x will add a trim function, but it will add a lot of other convenience utilities that back in '98 were considered "unnecessary" or too specialized.
|
479,312
| 479,336
|
product to decrease c++ compile time?
|
Are there any products that will decrease c++ build times? that can be used with msvc?
|
If it has to be a product, look at Xoreax IncrediBuild, which distributes the build to machines on the network.
Other than that:
solid build machines. RAM as it fits, use fast separate disks.
Splitting into separate projects (DLLs, Libraries). They can build in parallel, too
(use dual quad/core, and is easily bottlenecked by disk)
Intelligent use of headers, including precompiled headers. That's not easy, and often there are other stakeholders.
PIMPL helps, too.
|
479,332
| 479,507
|
How to get size and position of window caption buttons (minimise, restore, close)
|
Is there an API call to determine the size and position of window caption buttons? I'm trying to draw vista-style caption buttons onto an owner drawn window. I'm dealing with c/c++/mfc.
Edit: Does anyone have a code example to draw the close button?
|
I've found the function required to get the position of the buttons in vista: WM_GETTITLEBARINFOEX
This link also shows the system metrics required to get all the spacing correct (shame it's not a full dialog picture though). This works perfectly in Vista, and mostly in XP (in XP there is slightly too much of a gap between the buttons).
|
479,384
| 479,386
|
c++ cout autocase strings?
|
Is it possible to do something like cout << "my string"; and have my string capitalized? from what i can tell there is no way to do it? i need to wrap it around a function
|
Yes, you can extend std:streambuf
See this example: http://www.java2s.com/Tutorial/Cpp/0240__File-Stream/Extendsstdstreambuftocreateoutputbuffer.htm
|
479,431
| 516,642
|
Unit-tests for Boost.Spirit
|
I'm new to Boost.Spirit and Boost.Test and I would like to know how you verify the correctness of your grammars. Below is a simplified version of how I do it at the moment and I'm pretty sure that there's a better way:
Each test case hase a pair of two strings containing the text to parse and the expected result delimited by semicolons.
The parse functions does the actual parsing and returns a string which should be equal to the expected result.
std::string parse(std::string const & line) {
std::string name;
int hours;
rule<> top_rule = ... ; // rule assignes values to 'name' and 'hours'
parse_info<> info = parse(line.c_str(), top_rule);
if(info.full) {
std::stringstream sstr;
sstr << name << ";" << hours;
return sstr.str();
}
return "parser failed.";
}
BOOST_AUTO_TEST_SUITE( TestSuite )
BOOST_AUTO_TEST_CASE( TestCase ) {
BOOST_CHECK_EQUAL(parse("Tom worked for 10 hours."), "Tom;10");
}
BOOST_AUTO_TEST_SUITE_END()
|
In general, your approach seems fine to me. I would probably group class of tests into function with descriptive names, e.g. TestInvalidGrammar, TestErrorHandling, TestNestedGrammar etc. and have those called from the main.
I am sure you have read documentation but take a look at examples if it helps.
|
479,495
| 480,126
|
Visual Studio 2005 VB debugging with c++ dll - Mixed Language debugging
|
I have a vb project which calls functions in a dll.
The dll is created in a separate vs project (portaudio), which is written in c.
The dll c project compiles clean and builds the required dll, which I am currently dropping in c:\windows\system to vb runtime can see it.
VB Project lives in c:\devprojects\vbtest
C Project lives in c:\devprojects\portaudio with the project file in c:\devprojects\portaudio\build\msvc. Dll created in Win32\debug under this msvc directory.
When I call the dll function, is it possible for the vs debugger to step through the c function in the dll - I have all the code etc, but I don't know if VS2005 supports this kind of mixed language debugging.
If this is possible, could you advise how I should set up my Visual Studio to achieve this.
Many thanks
David
|
It is not necessary to have both projects in the same solution, but you should compile both projects with debug symbols enabled.
Now in your VB net solution Project/Properties, in the Debug tab make sure that "Enable unmanaged code debugging" is checked.
Also make sure that the dll loaded is in the same place where it was compiled, else it may not found the pdb where the debug symbols are stored.
|
479,634
| 479,930
|
Detect executable folder from SDL
|
I am creating a C++ SDL game engine, and it is relevant to know the executable path since images and other resources are not stored within the executable - they are in a separated folder("res/").
Under Linux, I am using a shell script "rungame.sh" that cd's to the executable path and then runs the executable(using then "./" to reference the executable folder).
However, I believe this is an "ugly" approach and I want it to be Windows-compatible.
Also, the current approach is not very good as it may change the meaning of some command line arguments.
I want a cross-platform(*NIX, Windows and Mac OS X, if possible) solution to get the current path of the executable. The game path/executable name may change.
What is the cleanest way to solve my problem (preferrably using std::string and as few platform-dependent APIs as possible)?
|
I strongly suggest searching before posting: How do I get the directory that a program is running from?
|
479,722
| 486,909
|
How to get current CPU and RAM usage in C++?
|
is it possible, in C++, to get the current RAM and CPU usage? Is there a platform-indepentent function call?
|
There is an open source library that gives these (and more system info stuff) across many platforms: SIGAR API
I've used it in fairly large projects and it works fine (except for certain corner cases on OS X etc.)
|
479,805
| 480,896
|
Visual C++ 2008 Express Edition error creating a new project
|
I have installed Visual C++ 2008 Express Edition on Vista Home Premium and whenever i try to create a new project, no mater which type(CLR, Console, Win32, Empty project) i get "Creating project 'project name' ... project creation failed." However i can open an existing solution.
So basically my Visual C++ is useless.
Any idea what could i do to get this working? I'd hate to be needed to reinstall the whole OS just to get it working.
I tried uninstalling and installing again multiple times. same error.
|
Solved following the steps in this guide: http://masteranza.wordpress.com/2008/12/27/solution-vs-c-2008-project-creation-failed-bug/ after a lot of Googleing
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.