question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,683,964 | 2,684,130 | identifying the type | In my application, there is a inheritance hierarchy in which only the classes that are at the end of the inheritance chain are non-abstract classes. Also there is some usage of boost::variant. I want to write a function which takes a pointer and a Type and says whether the object belongs to that type.
For example
#define IsA(nodeptr, type) ( checkType<type>(nodeptr) )
template<typename Type, bool isAbstract, typename PtrType >
class CheckType
{
bool operator()( PtrType* ptr ) { return ( typeid(*ptr) == typeid(Type) ); }
};
template<typename Type, typename PtrType >
class CheckType < Type, true, PtrType >
{
bool operator()( PtrType* ptr ) { return ( dynamic_cast<Type*>(ptr) != NULL ); }
};
template<typename Type, BOOST_VARIANT_ENUM_PARAMS(typename T) >
class CheckType< Type, false, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
{
bool operator()( boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>* ptr )
{
return ( ptr->type() == typeid(Type) );
}
}
template< typename Type, typename PtrType >
bool checkType( PtrType* nodePtr )
{
CheckType<Type, boost::is_abstract<PtrType>::value, PtrType> check;
return check(nodePtr);
}
Now if there is a boost variant, i want to find out whether the boost variant stores that particular type. Can someone help me with that? I don't want to add an extra parameter to find out whether it is a variant. Even for finding out the abstractness, i am using boost::is_abstract..
Thanks,
Gokul.
| Well there are two direct versions of this:
return (boost::get<Type*>(v) != 0);
And this:
return ( v.type() == typeid(Type) );
I am not sure how to handle that with your template overloading cleanly but you could do something like this:
template< typename Type, bool TypeisAbstract, bool TypeIsVariant,
typename ptrType >
bool checkType( ptrType* t)
{
return ( typeid(*t) == typeid(Type) );
}
template< typename Type, typename ptrType >
bool checkType<Type, true, false, ptrType>( ptrType* t)
{
return ( dynamic_cast<Type*>(t) != NULL );
}
template< typename Type>
bool checkType<Type, false, true, ptrType>(const boost::variant& v)
{
return ( v.type() == typeid(Type) );
}
|
2,684,508 | 2,686,137 | MOC adding namespace to class names | I have this very strange problem while compiling the project.
MOC seems to be adding a namespace to the class name being moc'ed, although it's not mentioned anywhere in the file/class.
The namespace, however, exists in a library which I use, but it's hidden far away in the header files and I don't use it in the UI files. This is what MOC generates:
const QMetaObject SmpTl::CaptureController::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_SmpTl__CaptureController,
qt_meta_data_SmpTl__CaptureController, 0 }};
The SmpTl namespace is not mentioned anywhere in the declaration of CaptureController, but it appears in the MOC-generated .cpp file.
I'm using Visual Studio with the QT integration.
| SmpTl is the namespace CaptureController is defined in, as it was found by MOC.
The Q_OBJECT macro expands into the declaration of the staticMetaObject-variable inside your class definition (among other things it expands into). The MOC-file contains the definition of that variable.
If this is not correct, please post your Qt version and a stripped down version of your header-file.
|
2,684,581 | 2,684,586 | C++ constructor behavior | I'm declaring an instance of a class like so:
Matrix m;
This appears to implicitly initialize m (i.e. run the constructor). Is this actually the case?
| Yes, the default constructor is called.
If there is no default constructor, this statement is ill-formed. If there are no user-declared constructors, the compiler provides a default constructor.
|
2,684,603 | 2,684,625 | how do I initialize a float to its max/min value? | How do I hard code an absolute maximum or minimum value for a float or double? I want to search out the max/min of an array by simply iterating through and catching the largest.
There are also positive and negative infinity for floats, should I use those instead? If so, how do I denote that in my code?
| You can use std::numeric_limits which is defined in <limits> to find the minimum or maximum value of types (As long as a specialization exists for the type). You can also use it to retrieve infinity (and put a - in front for negative infinity).
#include <limits>
//...
std::numeric_limits<float>::max();
std::numeric_limits<float>::min();
std::numeric_limits<float>::infinity();
As noted in the comments, min() returns the lowest possible positive value. In other words the positive value closest to 0 that can be represented. The lowest possible value is the negative of the maximum possible value.
There is of course the std::max_element and min_element functions (defined in <algorithm>) which may be a better choice for finding the largest or smallest value in an array.
|
2,684,938 | 2,870,412 | How can you animate a sprite in SFML | Lets say I have 4 images and I want to use these 4 images to animate a character. The 4 images represent the character walking. I want the animation to repeat itself as long as I press the key to move but to stop right when I unpress it. It doesn't need to be SFML specific if you don't know it, just basic theory would really help me.
Thank you.
| You may want some simple kind of state machine. When the key is down (see sf::Input's IsKeyDown method), have the character in the "animated" state. When the key is not down, have the character in "not animated" state. Of course, you could always skip having this "state" and just do what I mention below (depending on exactly what you're doing).
Then, if the character is in the "animated" state, get the next "image" (see the next paragraph for more details on that). For example, if you have your images stored in a simple 4 element array, the next image would be at (currentIndex + 1) % ARRAY_SIZE. Depending on what you are doing, you may want to store your image frames in a more sophisticated data structure. If the character is not in the "animated" state, then you wouldn't do any updating here.
If your "4 images" are within the same image file, you can use the sf::Sprite's SetSubRect method to change the portion of the image displayed. If you actually have 4 different images, then you probably would need to use the sf::Sprite's SetImage method to switch the images out.
|
2,684,971 | 2,685,065 | Context of Main function in C or C++ | Does the main function we define in C or C++ run in a process or thread.
If it runs in a thread, which process is responsible for spawning it
| main() is the entry point for your program. C++ (current C++ anyway) doesn't know what a process or thread is. The word 'process' is not even in the index of the standard. What happens before and after main() is mostly implementation defined. So, the answer to your question is also implementation defined.
In general though most operating systems have the concept of process and thread and they have similar meanings (though in Linux, for example, a thread is actually a "light weight process"). You can generally assume that your program will be started in a new process and that main() will then be called by the original thread after the implementation defined initialization.
Since there's plenty of room for the implementation and/or you to start up a whole bunch of threads before main is called though you will probably generally want to consider main() to have been called during the execution of a thread. The best way to think about it though is probably in terms of the standard unless you really have to think about the implementation. The standard doesn't currently know what a process or thread is. C++0x will change that in some way but I'm not sure at this point what the new concepts will be or how they will relate to OS specific constructs.
My answer is specifically addressed at the C++ language part of the question. C is a different language and I haven't used it in a good 10 years so I forget how the globals initialization is specified.
|
2,684,981 | 2,685,294 | How to place multiple formats on the clipboard? | For example, what Wordpad did when I press "Ctrl+C"?
It places many different format to clipboard. So Notepad can get the text without any color or font...etc, and you still can keep the original format when you paste in another Wordpad window.
The MSDN said I should call SetClipboardData multiple times. But it doesn't work at all.
| You can use Delphi's TClipboard.SetAsHandle to put data on the clipboard in as many formats as you want. Open the clipboard first, or else each call to SetAsHandle will clobber whatever else was already there, even in other formats.
Clipboard.Open;
Clipboard.SetAsHandle(cf_Text, x);
Clipboard.SetAsHandle(cf_Bitmap, y);
Clipboard.Close;
|
2,685,074 | 2,685,157 | Marshal a C++ class to C# | I need to access code in a native C++ DLL in some C# code but am having issues figuring out the marshaling. I've done this before with code that was straight C, but seem to have found that it's not directly possible with C++ classes. Made even more complicated by the fact that many of the classes contain virtual or inline functions. I even tried passing the headers through the PInvoke Interop Assistant, but it would choke on just about everything and not really no what to do... I'm guessing because it's not really supported.
So how, if at all possible, can you use a native C++ class DLL from .NET code.
If I have to use some intermediary (CLR C++?) that's fine.
| There is really no easy way to do this in C# - I'd recommend making a simple wrapper layer in C++/CLI that exposes the C++ classes as .NET classes.
It is possible to use P/Invoke and lots of cleverness to call C++ virtual methods, but I wouldn't go this route unless you really had no other choice.
|
2,685,094 | 2,686,603 | How to get a flat, non-interpolated color when using vertex shaders | Is there a way to achieve this (OpenGL 2.1)? If I draw lines like this
glShadeModel(GL_FLAT);
glBegin(GL_LINES);
glColor3f(1.0, 1.0, 0.0);
glVertex3fv(bottomLeft);
glVertex3fv(topRight);
glColor3f(1.0, 0.0, 0.0);
glVertex3fv(topRight);
glVertex3fv(topLeft);
.
.
(draw a square)
.
.
glEnd();
I get the desired result (a different colour for each edge) but I want to be able to calculate the fragment values in a shader. If I do the same after setting up my shader program I always get interpolated colors between vertices. Is there a way around this? (would be even better if I could get the same results using quads)
Thanks
| If you don't want the interpolation between vertice attributes inside a primitive (e.g. color in a line segment in your case) you'll need to pass the same color twice, so end up duplicating your geometry:
v0 v1 v2
x--------------x-----------x
(v0 is made of structs p0 and c0, v1 of p1 and c1 etc..)
For drawing the line with color interpolation:
glBegin(GL_LINES);
//draw first segment
glColor3fv(&c0); glVertex3fv(&p0);
glColor3fv(&c1); glVertex3fv(&p1);
//draw second segment
glColor3fv(&c1); glVertex3fv(&p1);
glColor3fv(&c2); glVertex3fv(&p2);
glEnd();
For drawing without interpolation:
glBegin(GL_LINES);
//draw first segment
glColor3fv(&c0); glVertex3fv(&p0);
glColor3fv(&c0); glVertex3fv(&p1);
//draw second segment
glColor3fv(&c1); glVertex3fv(&v1);
glColor3fv(&c1); glVertex3fv(&v2);
glEnd();
Note this mean you can no longer use GL_x_STRIP topology, since you don't want to share attributes inside a primitive.
|
2,685,104 | 2,702,674 | Output of gcc -fdump-tree-original | If I dump the code generated by GCC for a virtual destructor (with -fdump-tree-original), I get something like this:
;; Function virtual Foo::~Foo() (null)
;; enabled by -tree-original
{
<<cleanup_point <<< Unknown tree: expr_stmt
(void) (((struct Foo *) this)->_vptr.Foo = &_ZTV3Foo + 8) >>>
>>;
}
<D.20148>:;
if ((bool) (__in_chrg & 1))
{
<<cleanup_point <<< Unknown tree: expr_stmt
operator delete ((void *) this) >>>
>>;
}
My question is: where is the code after "<D.20148>:;" located? It is outside of the destructor so when is this code executed?
| That looks like the compiler-generated code to manage the actual memory deallocation after the destructor is called and should execute right after your destructor code.
|
2,685,172 | 2,685,193 | g++ no matching function call error | I've got a compiler error but I can't figure out why.
the .hpp:
#ifndef _CGERADE_HPP
#define _CGERADE_HPP
#include "CVektor.hpp"
#include <string>
class CGerade
{
protected:
CVektor o, rv;
public:
CGerade(CVektor n_o, CVektor n_rv);
CVektor getPoint(float t);
string toString();
};
the .cpp:
#include "CGerade.hpp"
CGerade::CGerade(CVektor n_o, CVektor n_rv)
{
o = n_o;
rv = n_rv.getUnitVector();
}
the error message:
CGerade.cpp:10: error: no matching function for call to ‘CVektor::CVektor()’
CVektor.hpp:28: note: candidates are: CVektor::CVektor(float, float, float)
CVektor.hpp:26: note: CVektor::CVektor(bool, float, float, float)
CVektor.hpp:16: note: CVektor::CVektor(const CVektor&)
CGerade.cpp:10: error: no matching function for call to ‘CVektor::CVektor()’
CVektor.hpp:28: note: candidates are: CVektor::CVektor(float, float, float)
CVektor.hpp:26: note: CVektor::CVektor(bool, float, float, float)
CVektor.hpp:16: note: CVektor::CVektor(const CVektor&)
| From the looks of it, your CVektor class has no default constructor, which CGerade uses in your constructor:
CGerade::CGerade(CVektor n_o, CVektor n_rv)
{ // <-- by here, all members are constructed
o = n_o;
rv = n_rv.getUnitVector();
}
You could (and probably should) add one, but better is to use the initialization list to initialize members:
CGerade::CGerade(CVektor n_o, CVektor n_rv) :
o(n_o),
rv(n_rv.getUnitVector())
{}
Which specifies how the members are initialized. (And above, it was defaulting to the non-existent default-constructor.)
|
2,685,238 | 2,685,329 | Are there any high level language that don't support using C++ libraries? | Are there any high level language that don't support using C++ libraries?
| Using C++ libraries from other high-level languages has a couple of major obstacles:
if the library is OO, you need to be able to create a C++ object in the calling language - this is not easy.
C++ implementations use a technique known as "name-mangling" to ensure type-safe linkage. Unfortunately, there is no standard for name mangling, so C++ code cannot even easily be called between different C++ implementations.
So the answer to your question is that most HLLs will have problems calling C++ code. They may also have problems calling any other language of course - there are actually no standardised binary interfaces between languages, except ad hoc, platform-specifc ones.
|
2,685,333 | 2,685,368 | Mapping C structure to an XML element | Suppose I have a structure in C or C++, such as:
struct ConfigurableElement {
int ID;
char* strName;
long prop1;
long prop2;
...
};
I would like to load/save it to/from the following XML element:
<ConfigurableElement ID="1" strName="namedElem" prop1="2" prop2="3" ... />
Such a mapping can be trivially done in Java/C# or any other language with run-time reflection for the matter. Can it be done in any non-tedious way in C++ with macros/template trickery?
Bonus points for handling nested structures/unions.
| The technique you want is called serialization. You may want to read these articles:
http://www.codeproject.com/KB/cpp/xmlserialization.aspx
http://www.codesynthesis.com/products/xsd/ <=== Very close to what you want!
http://www.artima.com/cppsource/xml_data_binding.html
http://www.ibm.com/developerworks/xml/library/x-serial.html
http://www.firstobject.com/xml-serialization-in-c++.htm
EDIT:
There is another option for you: Xmlize provided by Ultimatepp:
http://www.ultimatepp.org/reference$Xmlize.html
http://www.ultimatepp.org/reference$Xmlize$en-us.html
http://www.ultimatepp.org/reference$XmlizeCustomValue$en-us.html
http://www.ultimatepp.org/reference$Xmlize_std$en-us.html
http://www.ultimatepp.org/reference$XML$en-us.html
|
2,685,336 | 2,685,397 | Running an XLL outside Excel? | I know this question has been posted before... but I haven't found any answer yet (besides from the generic answers about how XLL are actually DLL, etc).
Has anybody out there been successful calling a XLL from say C# (using DllImport) without having to load Excel with the XLL loaded as an addin?
Basically, you would have to create a special XLCALL32.DLL that simulates the Excel host. It sounds like a lot of work... has anybody done this? Or seen a product to do it?
Thanks
| You're on the right track with needing to create your own XLCall32.dll and simulate Excel. That's non-trivial given what you can do via the interface that XLLs use to talk to Excel. It becomes easier the less of Excel that you need to use from within your XLL, so I guess if you have a known selection of XLLs that you need to use and you know what bits of Excel they access via the XLL interface then you can just replace the bits you need...
Why do you want to do this?
|
2,685,506 | 2,685,605 | C++ STL question related to insert iterators and overloaded operators | #include <list>
#include <set>
#include <iterator>
#include <algorithm>
using namespace std;
class MyContainer {
public:
string value;
MyContainer& operator=(const string& s) {
this->value = s;
return *this;
}
};
int main()
{
list<string> strings;
strings.push_back("0");
strings.push_back("1");
strings.push_back("2");
set<MyContainer> containers;
copy(strings.begin(), strings.end(), inserter(containers, containers.end()));
}
The preceeding code does not compile. In standard C++ fashion the error output is verbose and difficult to understand. The key part seems to be this...
/usr/include/c++/4.4/bits/stl_algobase.h:313: error: no match for ‘operator=’ in ‘__result.std::insert_iterator::operator* [with _Container = std::set, std::allocator >]() = __first.std::_List_iterator::operator* [with _Tp = std::basic_string, std::allocator >]()’
...which I interpet to mean that the assignment operator needed is not defined. I took a look at the source code for insert_iterator and noted that it has overloaded the assignment operator. The copy algorithm must uses the insert iterators overloaded assignment operator to do its work(?).
I guess that because my input iterator is on a container of strings and my output iterator is on a container of MyContainers that the overloaded insert_iterator assignment operator can no longer work.
This is my best guess, but I am probably wrong.
So, why exactly does this not work and how can I accomplish what I am trying to do?
| What would work would be using the constructor (which would make more sense instead of the assignment):
class MyContainer {
public:
string value;
MyContainer(const string& s): value(s) {
}
};
Then the second problem is that set also requires its contents to be comparable.
As to the cause, insert_iterator works by overloading operator=:
insert_iterator<Container>& operator= (typename Container::const_reference value);
As you can see, the righthand value must be either the value type of the container or implicitly convertible to it, which is exactly what a (non-explicit) constructor achieves and the assignment operator doesn't.
Technically you could also make it work without changing the class (e.g if you don't want an non-explicit constructor) by providing a suitable conversion function:
MyContainer from_string(const std::string& s)
{
MyContainer m;
m = s; //or any other method how to turn a string into MyContainer
return m;
}
which can be used with std::transform:
transform(strings.begin(), strings.end(), inserter(containers, containers.end()), from_string);
|
2,685,555 | 2,685,569 | Passing a structure by value, with another structure as one of its members, changes values of this member's members | Sorry for the confusing title, but it basically says it all. Here's the structures I'm using (found in OpenCV) :
struct CV_EXPORTS CvRTParams : public CvDTreeParams
{
bool calc_var_importance;
int nactive_vars;
CvTermCriteria term_crit;
CvRTParams() : CvDTreeParams( 5, 10, 0, false, 10, 0, false, false, 0 ),
calc_var_importance(false), nactive_vars(0)
{
term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 50, 0.1 );
}
}
and
typedef struct CvTermCriteria
{
int type;
int max_iter;
double epsilon;
}
CvTermCriteria;
CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon )
{
CvTermCriteria t;
t.type = type;
t.max_iter = max_iter;
t.epsilon = (float)epsilon;
return t;
}
Now, I initialize a CvRTParams structure and set values for its members :
CvRTParams params;
params.max_depth = 8;
params.min_sample_count = 10;
params.regression_accuracy = 0;
params.use_surrogates = false;
params.max_categories = 10;
params.priors = priors;
params.calc_var_importance = true;
params.nactive_vars = 9;
params.term_crit.max_iter = 33;
params.term_crit.epsilon = 0.1;
params.term_crit.type = 3;
Then call a function of an object, taking params in as a parameter :
CvRTrees* rt = new CvRTrees;
rt->train(t, CV_ROW_SAMPLE, r, 0, 0, var_type, 0, params);
What happens now ? Values of...
params.term_crit.max_iter
params.term_crit.epsilon
params.term_crit.type
have changed ! They are no longer 33, 0.1 and 3, but something along the lines of 3, 7.05541e-313 and 4, and this, for the whole duration of the CvRtrees::train() function...
| By the time I finished writing this question I found the answer. So I figured I'd post anyway if someone comes across the same problem. The code itself wasn't wrong (or at least, it wasn't completely wrong). However I am using MacOS X and apple-gcc on a ppc processor (G5). I was using the -fast flag for optimization. Removing the -fast flag (leaving only -O3) solved the problem.
|
2,685,598 | 2,685,683 | #warning in Visual Studio | In gcc I can do compile-time warnings like this:
#if !defined(_SOME_FEATURE_)
#warning _SOME_FEATURE_ not defined-- be careful!
#endif
But in Visual Studio this doesn't work. Is there an alternative syntax for #warning?
| About the closest equivalent would be #pragma message, or possibly #error (the latter stops compilation, the former just prints out the specified error message).
|
2,685,626 | 2,686,021 | Explain Type Classes in Haskell | I am a C++ / Java programmer and the main paradigm I happen to use in everyday programming is OOP. In some thread I read a comment that Type classes are more intuitive in nature than OOP. Can someone explain the concept of type classes in simple words so that an OOP guy like me can understand it?
| First, I am always very suspicious of claims that this or that program structure is more intuitive. Programming is counter-intuitive and always will be because people naturally think in terms of specific cases rather than general rules. Changing this requires training and practice, otherwise known as "learning to program".
Moving on to the meat of the question, the key difference between OO classes and Haskell typeclasses is that in OO a class (even an interface class) is both a type and a template for new types (descendants). In Haskell a typeclass is only a template for new types. More precisely, a typeclass describes a set of types that share a common interface, but it is not itself a type.
So the typeclass "Num" describes numeric types with addition, subtraction and multiplication operators. The "Integer" type is an instance of "Num", meaning that Integer is a member of the set of types that implement those operators.
So I can write a summation function with this type:
sum :: Num a => [a] -> a
The bit to to the left of the "=>" operator says that "sum" will work for any type "a" that is an instance of Num. The bit to the right says it takes a list of values of type "a" and returns a single value of type "a" as a result. So you could use it to sum a list of Integers or a list of Doubles or a list of Complex, because they are all instances of "Num". The implementation of "sum" will use the "+" operator of course, which is why you need the "Num" type constraint.
However you cannot write this:
sum :: [Num] -> Num
because "Num" is not a type.
This distinction between type and typeclass is why we don't talk about inheritance and descendants of types in Haskell. There is a sort of inheritance for typeclasses: you can declare one typeclass as a descendant of another. The descendant here describes a subset of the types described by parent.
An important consequence of all this is that you can't have heterogenous lists in Haskell. In the "sum" example you can pass it a list of integers or a list of doubles, but you cannot mix doubles and integers in the same list. This looks like a tricky restriction; how would you implement the old "cars and lorries are both types of vehicle" example? There are several answers depending on the problem you are actually trying to solve, but the general principle is that you do your indirection explicitly using first-class functions rather than implicitly using virtual functions.
|
2,685,636 | 2,705,220 | Lua, game state and game loop |
Call main.lua script at each game loop iteration - is it good or bad design? How does it affect on the performance (relatively)?
Maintain game state from a. C++ host-program or b. from Lua scripts or c. from both and synchronise them?
(Previous question on the topic: Lua and C++: separation of duties)
(I vote for every answer. The best answer will be accepted.)
| The best thing about lua is that it has a lightweight VM, and after the chunks get precompiled running them in the VM is actually quite fast, but still not as fast as a C++ code would be, and I don't think calling lua every rendered frame would be a good idea.
I'd put the game state in C++, and add functions in lua that can reach, and modify the state. An event based approach is almost better, where event registering should be done in lua (preferably only at the start of the game or at specific game events, but no more than a few times per minute), but the actual events should be fired by C++ code. User inputs are events too, and they don't usually happen every frame (except for maybe MouseMove but which should be used carefully because of this). The way you handle user input events (whether you handle everything (like which key was pressed, etc) in lua, or whether there are for example separate events for each keys on the keyboard (in an extreme case) depends on the game you're trying to make (a turn based game might have only one event handler for all events, an RTS should have more events, and an FPS should be dealt with care (mainly because moving the mouse will happen every frame)). Generally the more separate kinds of events you have, the less you have to code in lua (which will increase performance), but the more difficult it gets if a "real event" you need to handle is actually triggered by more separate "programming level events" (which might actually decrease performance, because the lua code needs to be more complex).
Alternatively if performance is really important you can actually improve the lua VM by adding new opcodes to it (I've seen some of the companies to do this, but mainly to make decompilation of the compiled lua chunks more harder), which is actually not a hard thing to do. If you have something that the lua code needs to do a lot of times (like event registering, event running, or changing the state of the game) you might want to implement them in the lua VM, so instead of multiple getglobal and setglobal opcodes they would only take one or two (for example you could make a SETSTATE opcode with a 0-255 and a 0-65535 parameter, where the first parameter descibes which state to modify, and the second desribes the new value of the state. Of course this only works if you have a maximum of 255 events, with a maximum of 2^16 values, but it might be enough in some cases. And the fact that this only takes one opcode means that the code will run faster). This would also make decompilation more harder if you intend to obscure your lua code (although not much to someone who knows the inner workings of lua). Running a few opcodes per frame (around 30-40 tops) won't hit your performance that badly. But 30-40 opcodes in the lua VM won't get you far if you need to do really complex things (a simple if-then-else can take up to 10-20 or more opcodes depending on the expression).
|
2,685,679 | 2,685,765 | Parse int to string with stringstream | Well!
I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution.
I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999].
As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream.
So my code looked like this:
// tempTotal is my int value I want converted.
void toString( int tempTotal, string &str )
{
ostringstream ss; // C++ Standard compliant method.
ss << tempTotal;
str = ss.str(); // Overwrite referenced value of given string.
}
and the function calling it was:
else
{
toString( tempTotal, store );
cout << loop1 << " x " << loop2 << "= " << store << endl;
}
So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there.
Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal.
All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know.
So even though I feel this is a really, really lame question, I just have to ask:
How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.
EDIT:
Wow. Seriously. This is kind of embarrassing. I forgot to set my tempTotal variable to something. It was uninitialized, so therefore I couldn't copy anything and the reason the program gave me either a 0 or nothing at all.
Hope people can have a laugh though, so I think this question would now be better suited for deletion since it doesn't really serve a purpose unless xD But thanks to everybody who tried to help me!
| Have you tried just outputting the integer as is? If you're only converting it to a string to output it, then don't bother since cout will do that for you.
else
{
// toString( tempTotal, store ); // Skip this step.
cout << loop1 << " x " << loop2 << "= " << tempTotal << endl;
}
I have a feeling that it's likely that tempTotal doesn't have the value you think it has.
|
2,685,808 | 2,686,047 | Need advice on C++ coding pattern | Hi!
I have a working prototype of a game engine and right now I'm doing some refactoring.
What I'm asking for is your opinion on usage of the following C++ coding patterns.
I have implemented some trivial algorithms for collision detection and they are implemented the following way:
Not shown here - class constructor is made private and using algorithms looks like Algorithm::HandleInnerCollision(...)
class Algorithm {
// Private routines
static bool is_inside(Point& p, Object& object) {
// (...)
}
public:
/**
* Handle collision where the moving object should be always
* located inside the static object
*
* @param MovingObject & mobject
* @param const StaticObject & sobject
* @return void
* @see
*/
static void HandleInnerCollision(MovingObject& mobject, const StaticObject& sobject) {
// (...)
}
So, my question is - somebody advised me to do it "the C++" way - so that all functions are wrapped in a namespace, but not in a class. Is there some good way to preserve privating if I will wrap them into a namespace as adviced?
What I want to have is a simple interface and ability to call functions as Algorithm::HandleInnerCollision(...) while not polluting the namespace with other functions such as is_inside(...)
Of, if you can advise any alternative design pattern for such kind of logics, I would really appreciate that...
| If the various functions have something to do with each other, if it's more than helping but really have a common factor such as acting on the same entity, then put them in a class. On the other hand, if a function acts on the same entity as others, but you also want to reuse it for other entities that are convertible to the first entity then extract it outside of the class:
bool same_size(const shape& a, const shape& b)
{
return a.bounding_x == b.bounding_x && a.bounding_y == b.bounding_y;
}
The above function will work with any two objects that are convertible to or descend from shape.
Put functionality that you don't want to share with other translation units (i.e. helper functions and help objects) in an unnamed namespace. This is the C++ equivalent of the C static functions, and it instructs the compiler to keep anything inside the unnamed namespace private to this translation unit.
namespace {
bool is_inside(Point& p, Object& object)
{
// ...
}
// ...
}
Put all the functionality that you want to share with other translation units in a named namespace. This will instruct the compiler to wrap the code with a common name, so names don't collide with external code (libraries etc.) names.
namespace kotti {
void HandleInnerCollision(MovingObject& mobject,
const StaticObject& sobject)
{
// ...
}
// ...
}
|
2,685,854 | 2,685,871 | Why should the copy constructor accept its parameter by reference in C++? | Why must a copy constructor's parameter be passed by reference?
| Because if it's not by reference, it's by value. To do that you make a copy, and to do that you call the copy constructor. But to do that, we need to make a new value, so we call the copy constructor, and so on...
(You would have infinite recursion because "to make a copy, you need to make a copy".)
|
2,685,917 | 2,686,076 | Is it possible that an C++ application use CRT 4053 when the manifest uses 762? | My application is compiled on a development PC with a manifest 762:
However at runtime, on another release PC, the application uses the 4053 version of the file.
c:\windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.4053_x-ww_e6967989\MSVCR80.DLL
Somewhere along the execution of my application I get a runtime error pointing to the msvcr80.dll. I suspect that the problem might be caused because the application use a DLL at runtime that was not used during the build.
If I check in the WinSxS folder of the release PC I have both 762 and 4053 version of the CRT. Why does the application uses 4053 instead of the one used in the manifest?
Thanks.
| Because of a "publisher policy" that redirects requested DLL versions. Your manifest should not ask for 762 anymore, it's got cooties. You'll need to deploy the security update to your machine so the vc\include\crtassem.h gets updated.
|
2,685,977 | 2,685,999 | Memory randomization as application security enhancement? | I recently came upon a Microsoft article that touted new "defensive enhancements" of Windows 7. Specifically:
Address space layout randomization (ASLR)
Heap randomization
Stack randomization
The article went on to say that "...some of these defenses are in the core operating system, and the Microsoft Visual C++ compiler offers others" but didn't explain how these strategies would actually increase security.
Anyone know why memory randomization increases security, if at all? Do other platforms and compilers employ similar strategies?
| It increases security by making it hard to predict where something will be in memory. Quite a few buffer overflow exploits work by putting (for example) the address of a known routine on the stack, and then returning to it. It's much harder to do that without knowing the address of the relevant routine.
As far as I know, OpenBSD was about the first to do this, at least among the reasonably well-known OSes for PCs.
|
2,686,096 | 2,686,150 | C++ Get Username From Process | I have a process handle with
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, THE_PROCESS_ID);
How can I get the username of the user that is running the process?
I am using unmanaged code (no .NET).
| Use OpenProcessToken to get the token (obviously), then GetTokenInformation with the TokenOwner flag to get the SID of the owner. Then you can use LookupAccountSid to get the username.
|
2,686,146 | 2,686,171 | Simple C++ container class that is thread-safe for writing | I am writing a multi-threaded program using OpenMP in C++. At one point my program forks into many threads, each of which need to add "jobs" to some container that keeps track of all added jobs. Each job can just be a pointer to some object.
Basically, I just need the add pointers to some container from several threads at the same time.
Is there a simple solution that performs well? After some googling, I found that STL containers are not thread-safe. Some stackoverflow threads address this question, but none that forms a consensus on a simple solution.
| There's no built-in way to do this. You can simply use a lock to guard one of the existing container types. It might be a better idea to have each thread use it's own container, then combine the results together in the end.
|
2,686,230 | 2,686,347 | GDI+ With C++Builder? | How do I use GDI+ with C++Builder? Can someone give me a simple example of creating a surface and drawing a circle on it?
| It would be similar to coding a normal Windows program in C using Visual Studio.
Basically:
include "gdiplus.h"
link to gdiplus.lib
call GdiPlusStartup at the start of your program (before main window creation)
call GdiPlusShutdown at the end of your program (after the message loop has ended and the main window's been destroyed)
Here's a link with a sample program:
http://msdn.microsoft.com/en-us/library/ms533895(v=VS.85).aspx
MSDN contains much information on this topic:
http://msdn.microsoft.com/en-us/library/ms533802(v=VS.85).aspx
|
2,686,400 | 2,686,412 | Can I create functions without defining them in the header file? | Can I create a function inside a class without defining it in the header file of that class?
| Why don't you try and see?
[˙ʇ,uɐɔ noʎ 'oᴎ]
Update: Just to reflect on the comments below, with the emphasis of the C++ language on smart compiling, the compiler needs to know the size of the class (thus requiring declaration of all member data) and the class interface (thus requiring all functions and types declaration).
If you want the flexibility of adding functions to the class without the need to change the class header then consider using the pimpl idiom. This will, however, cost you the extra dereference for each call or use of the function or data you added. There are various common reasons for implementing the pimpl:
to reduce compilation time, as this allows you to change the class without changing all the compilation units that depend on it (#include it)
to reduce coupling between a class' dependents and some often-changing implementation details of the class.
as Noah Roberts mentioned below the pimpl can also solve exception safety issues.
|
2,686,429 | 2,695,419 | Another design-related C++ question | Hi!
I am trying to find some optimal solutions in C++ coding patterns, and this is one of my game engine - related questions.
Take a look at the game object declaration (I removed almost everything, that has no connection with the question).
// Abstract representation of a game object
class Object :
public Entity,
IRenderable, ISerializable {
// Object parameters
// Other not really important stuff
public:
// @note Rendering template will never change while
// the object 'lives'
Object(RenderTemplate& render_template, /* params */) : /*...*/ { }
private:
// Object rendering template
RenderTemplate render_template;
public:
/**
* Default object render method
* Draws rendering template data at (X, Y) with (Width, Height) dimensions
*
* @note If no appropriate rendering method overload is specified
* for any derived class, this method is called
*
* @param Backend & b
* @return void
* @see
*/
virtual void Render(Backend& backend) const {
// Render sprite from object's
// rendering template structure
backend.RenderFromTemplate(
render_template,
x, y, width, height
);
}
};
Here is also the IRenderable interface declaration:
// Objects that can be rendered
interface IRenderable {
/**
* Abstract method to render current object
*
* @param Backend & b
* @return void
* @see
*/
virtual void Render(Backend& b) const = 0;
}
and a sample of a real object that is derived from Object (with severe simplifications :)
// Ball object
class Ball : public Object {
// Ball params
public:
virtual void Render(Backend& b) const {
b.RenderEllipse(/*params*/);
}
};
What I wanted to get is the ability to have some sort of standard function, that would draw sprite for an object (this is Object::Render) if there is no appropriate overload.
So, one can have objects without Render(...) method, and if you try to render them, this default sprite-rendering stuff is invoked. And, one can have specialized objects, that define their own way of being rendered.
I think, this way of doing things is quite good, but what I can't figure out -
is there any way to split the objects' "normal" methods (like Resize(...) or Rotate(...)) implementation from their rendering implementation?
Because if everything is done the way described earlier, a common .cpp file, that implements any type of object would generally mix the Resize(...), etc methods implementation and this virtual Render(...) method and this seems to be a mess. I actually want to have rendering procedures for the objects in one place and their "logic implementation" - in another.
Is there a way this can be done (maybe alternative pattern or trick or hint) or this is where all this polymorphic and virtual stuff sucks in terms of code placement?
| In this particular example, I'm not sure that it's desirable to separate Resize from Render, since Resize has a direct impact on the rendered image.
The way I do it is make the Entitys contain the Renderable. E.g. an Entity would have a member variable that is the sprite to be rendered. When the entity becomes visible, it hands the sprite to the rendering system and says, basically, "ok draw this each frame until I tell you to stop," although the rendering engine does culling of off-screen objects and other madness. Perhaps obviously, the rendering engine then maintains a list of renderable things (or maybe several lists if you want to split sprites from lines or particles for rendering efficiency), and then it just churns through that much less complicated list of items when it's time to do the draw.
That way, the entity can control the renderable, it can scale it or rotate it (i.e. manipulate its rendering matrix), but it doesn't need to decide when it's appropriate to draw it beyond whether or not it is "alive". The rendering engine, though, only knows how to draw the item in question and doesn't need knowledge of your entity graph.
|
2,686,542 | 2,686,571 | Converting integer to a bit representation | How can I convert a integer to its bit representation. I want to take an integer and return a vector that has contains 1's and 0's of the integer's bit representation.
I'm having a heck of a time trying to do this myself so I thought I would ask to see if there was a built in library function that could help.
| Doesn't work with negatives.
vector<int> convert(int x) {
vector<int> ret;
while(x) {
if (x&1)
ret.push_back(1);
else
ret.push_back(0);
x>>=1;
}
reverse(ret.begin(),ret.end());
return ret;
}
|
2,686,548 | 2,686,618 | Sorting eigenvectors by their eigenvalues (associated sorting) | I have an unsorted vector of eigenvalues and a related matrix of eigenvectors. I'd like to sort the columns of the matrix with respect to the sorted set of eigenvalues. (e.g., if eigenvalue[3] moves to eigenvalue[2], I want column 3 of the eigenvector matrix to move over to column 2.)
I know I can sort the eigenvalues in O(N log N) via std::sort. Without rolling my own sorting algorithm, how do I make sure the matrix's columns (the associated eigenvectors) follow along with their eigenvalues as the latter are sorted?
| Typically just create a structure something like this:
struct eigen {
int value;
double *vector;
bool operator<(eigen const &other) const {
return value < other.value;
}
};
Alternatively, just put the eigenvalue/eigenvector into an std::pair -- though I'd prefer eigen.value and eigen.vector over something.first and something.second.
|
2,686,601 | 2,686,642 | operator << : std::cout << i << (i << 1); | I use the stream operator << and the bit shifting operator << in one line.
I am a bit confused, why does code A) not produce the same output than code B)?
A)
int i = 4;
std::cout << i << " " << (i << 1) << std::endl; //4 8
B)
myint m = 4;
std::cout << m << " " << (m << 1) << std::endl; //8 8
class myint:
class myint {
int i;
public:
myint(int ii) {
i = ii;
}
inline myint operator <<(int n){
i = i << n;
return *this;
}
inline operator int(){
return i;
}
};
thanks in advance
Oops
| Your second example is undefined behavior.
You have defined the << operator on your myint class as if it were actually <<=. When you execute i << 1, the value in i is not modified, but when you execute m << 1, the value in m is modified.
In C++, it is undefined behavior to both read and write (or write more than once) to a variable without an intervening sequence point, which function calls and operators are not, with respect to their arguments. It is nondeterministic whether the code
std::cout << m << " " << (m << 1) << std::endl;
will output the first m before or after m is updated by m << 1. In fact, your code may do something totally bizarre, or crash. Undefined behavior can lead to literally anything, so avoid it.
One of the proper ways to define the << operator for myint is:
myint operator<< (int n) const
{
return myint(this->i << n);
}
(the this-> is not strictly necessary, just my style when I overload operators)
|
2,687,017 | 2,709,950 | Boost Shared Pointer: Simultaneous Read Access Across Multiple Threads | I have a thread A which allocates memory and assigns it to a shared pointer. Then this thread spawns 3 other threads X, Y and Z and passes a copy of the shared pointer to each. When X, Y and Z go out of scope, the memory is freed. But is there a possibility that 2 threads X, Y go out of scope at the exact same point in time and there is a race condition on reference count so instead of decrementing it by 2, it only gets decremented once. So, now the reference count newer drops to 0, so there is a memory leak. Note that, X, Y and Z are only reading the memory. Not writing or resetting the shared pointer. To cut a long story short, can there be a race condition on the reference count and can that lead to memory leaks?
| Several others have already provided links to the documentation explaining that this is safe.
For absolutely irrefutable proof, see how Boost Smartptr actually implements its own mutexes from scratch in boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp (or your platform's corresponding file).
|
2,687,208 | 2,687,236 | looser throw specifier for in C++ | I am getting an error that says:
error: looser throw specifier for 'virtual CPLAT::CP_Window::~CP_Window()'
On the destructor, I have never heard of this before and some Google Searches say this might be a GCC 4 problem, which I would not be sure how to work around since I need GCC 4 to build a Universal Binary.
My Environment: OS X 10.6, XCode 3.2.2, GCC 4 to build a universal binary.
What is the issue?
| I assume that CPLAT has a base class? I'm also guessing that you did not put a throw specifier on CPLAT's destructor?
You can put throw(X) (where X is a comma-separated list of exceptions) at the end of a function's signature to indicate what exceptions it's allowed to throw. If you put throw() as the throw specifier, then it would indicate that no exceptions can be thrown from that function. It's fairly common to do this with destructors since you don't ever want a destructor to throw an exception.
A class that overrides a function which has a throw specifier cannot have a looser throw specifier (list more exceptions) than the function being overridden, since that would indicate that the derived class' function could violate the throw specifier of the base class' function. Not having a throw specifier means that any exception can be thrown from that function, so it's as loose as it can get.
In all likelihood, you need to add throw() to the end of the function signature of CPLAT's destructor.
Edit: By the way, I should probably add that you probably don't want to use throw specifiers (other than throw() on destructors) without really knowing that that's what you want. Unlike Java's checked exceptions, they're not caught at compile-time but rather terminate your program at runtime if violated. So, it's best not to use them unless you know what you're doing.
|
2,687,284 | 2,687,336 | Why won't this compile and how can it be implemented so that it does? | Here is some C++ code I'm playing around with:
#include <iostream>
#include <vector>
#define IN ,
#define FOREACH(x,y) for(unsigned int i=0;i<y.size();i++) { x=y[i];
#define ENDFOREACH }
using namespace std;
int main()
{
vector<int> ints;
ints.push_back(3);
ints.push_back(4);
ints.push_back(5);
ints.push_back(6);
FOREACH(int item IN ints)
cout << item;
ENDFOREACH
return 0;
}
However, I get an error:
macro "FOREACH" requires 2 arguments, but only 1 given
The code compiles if I change the IN to a comma. How can I get the IN to take the place of a comma?
Update: for those interested, here is the final version, which, if I do say so myself, is quite nice.
#include <iostream>
#include <vector>
#define in ,
#define as ,
#define FOREACH_(x,y,z) \
y x; \
if(z.size()) x = z[0]; \
for(unsigned int i=0,item;i<z.size();i++,x=z[i])
#define foreach(x) FOREACH_(x)
using namespace std;
int main()
{
vector<int> ints;
ints.push_back(3);
ints.push_back(4);
ints.push_back(5);
ints.push_back(6);
foreach(item as int in ints)
{
cout << item << endl;
}
return 0;
}
| Others have already explained why it doesn't compile as is.
In order to make it work you have to give that IN a chance to turn into a comma. For that you can introduce an extra level of "indirection" in your macro definition
#define IN ,
#define FOREACH_(x,y) for(unsigned int i=0;i<y.size();i++) { x=y[i];
#define FOREACH(x) FOREACH_(x)
#define ENDFOREACH }
In this case you'll have to use some substitute for comma (like your IN) and can no longer specify comma explicitly. I.e. now this
FOREACH(int item IN ints)
cout << item;
ENDFOREACH
compiles fine, while
FOREACH(int item, ints)
cout << item;
ENDFOREACH
does not.
|
2,687,304 | 2,687,319 | CP_EXPORT in class declaration in C++ | What does it mean when a class is declared like this:
class CP_EXPORT CP_Window : public CP_Window_Imp
What does the CP_EXPORT portion mean/imply?
| CP_EXPORT is most probably a macro to conditionally export or import the class from a dynamic library.
For example, when using Visual C++, a macro is used to conditionally select between using dllexport and dllimport. This allows the same header to be used for both the project building the DLL itself and any projects that link against or load the DLL.
|
2,687,342 | 2,687,964 | How can I get this code involving unique_ptr to compile? | #include <vector>
#include <memory>
using namespace std;
class A {
public:
A(): i(new int) {}
A(A const& a) = delete;
A(A &&a): i(move(a.i)) {}
unique_ptr<int> i;
};
class AGroup {
public:
void AddA(A &&a) { a_.emplace_back(move(a)); }
vector<A> a_;
};
int main() {
AGroup ag;
ag.AddA(A());
return 0;
}
does not compile... (says that unique_ptr's copy constructor is deleted)
I tried replacing move with forward. Not sure if I did it right, but it didn't work for me.
[~/nn/src] g++ a.cc -o a -std=c++0x
/opt/local/include/gcc44/c++/bits/unique_ptr.h: In member function 'A& A::operator=(const A&)':
a.cc:6: instantiated from 'void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, _Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
/opt/local/include/gcc44/c++/bits/vector.tcc:100: instantiated from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
a.cc:17: instantiated from here
/opt/local/include/gcc44/c++/bits/unique_ptr.h:219: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>& std::unique_ptr<_Tp, _Tp_Deleter>::operator=(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_Deleter = std::default_delete<int>]'
a.cc:6: error: used here
In file included from /opt/local/include/gcc44/c++/vector:69,
from a.cc:1:
/opt/local/include/gcc44/c++/bits/vector.tcc: In member function 'void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, _Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]':
/opt/local/include/gcc44/c++/bits/vector.tcc:100: instantiated from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = A, _Tp = A, _Alloc = std::allocator<A>]'
a.cc:17: instantiated from here
/opt/local/include/gcc44/c++/bits/vector.tcc:314: note: synthesized method 'A& A::operator=(const A&)' first required here
| Probably your standard library doesn't (yet) define unique_ptr<T>::unique_ptr(unique_ptr &&). I checked my headers in 4.5 and it's there, so maybe try upgrading.
When it fails to find the move constructor, it would look for the copy constructor and find it deleted.
I get other errors when I compile that, though.
EDIT: Got it to work. I don't understand why you have to move an object which is already an rvalue reference, but you do. The only problem was a missing assigment operator.
#include <vector>
#include <memory>
using namespace std;
class A {
public:
A(): i(new int) {}
A(A const& a) = delete;
A &operator=(A const &) = delete;
A(A &&a): i(move(a.i)) {}
A &operator=(A &&a ) { i = move(a.i); }
unique_ptr<int> i;
};
class AGroup {
public:
void AddA(A &&a) { a_.emplace_back(move(a)); }
vector<A> a_;
};
int main() {
AGroup ag;
ag.AddA(A());
return 0;
}
|
2,687,392 | 18,514,815 | Is it possible to declare two variables of different types in a for loop? | Is it possible to declare two variables of different types in the initialization body of a for loop in C++?
For example:
for(int i=0,j=0 ...
defines two integers. Can I define an int and a char in the initialization body? How would this be done?
| C++17: Yes! You should use a structured binding declaration. The syntax has been supported in gcc and clang since gcc-7 and clang-4.0 (clang live example). This allows us to unpack a tuple like so:
for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"ab"}}; i < N; ++i, f += 1.5) {
// ...
}
The above will give you:
int i set to 1
double f set to 1.0
std::string s set to "ab"
Make sure to #include <tuple> for this kind of declaration.
You can specify the exact types inside the tuple by typing them all out as I have with the std::string, if you want to name a type. For example:
auto [vec, i32] = std::tuple{std::vector<int>{3, 4, 5}, std::int32_t{12}}
A specific application of this is iterating over a map, getting the key and value,
std::unordered_map<K, V> m = { /*...*/ };
for (auto& [key, value] : m) {
// ...
}
See a live example here
C++14: You can do the same as C++11 (below) with the addition of type-based std::get. So instead of std::get<0>(t) in the below example, you can have std::get<int>(t).
C++11: std::make_pair allows you to do this, as well as std::make_tuple for more than two objects.
for (auto p = std::make_pair(5, std::string("Hello World")); p.first < 10; ++p.first) {
std::cout << p.second << '\n';
}
std::make_pair will return the two arguments in a std::pair. The elements can be accessed with .first and .second.
For more than two objects, you'll need to use a std::tuple
for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
std::get<0>(t) < 10;
++std::get<0>(t)) {
std::cout << std::get<1>(t) << '\n'; // cout Hello world
std::get<2>(t).push_back(std::get<0>(t)); // add counter value to the vector
}
std::make_tuple is a variadic template that will construct a tuple of any number of arguments (with some technical limitations of course). The elements can be accessed by index with std::get<INDEX>(tuple_object)
Within the for loop bodies you can easily alias the objects, though you still need to use .first or std::get for the for loop condition and update expression
for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
std::get<0>(t) < 10;
++std::get<0>(t)) {
auto& i = std::get<0>(t);
auto& s = std::get<1>(t);
auto& v = std::get<2>(t);
std::cout << s << '\n'; // cout Hello world
v.push_back(i); // add counter value to the vector
}
C++98 and C++03 You can explicitly name the types of a std::pair. There is no standard way to generalize this to more than two types though:
for (std::pair<int, std::string> p(5, "Hello World"); p.first < 10; ++p.first) {
std::cout << p.second << '\n';
}
|
2,687,420 | 2,687,615 | Doxygen ignoring inherited functions, when class inherits privately but the functions declared public again | Sorry for long winded title, this makes a lot more sense with an example.
Suppose we have a class A:
class A {
public:
void someFunction();
void someOtherFunction();
};
And another class that privately inherits from A. However, we re-declare one of the inherited functions as public:
class B : private A {
public:
A::someFunction;
}
When this code is processed by Doxygen, it does not recognise the public declaration of someFunction in class B. Instead, it shows someFunction as a privately inherited function. This is incorrect.
Is anybody aware of how to fix this?
Cheers
| I can't comment so I'll post this as an answer.
When you do private inheritance in C++, it's a variant of composition or agregation. It's like a "Car - has an - Engine" relationship, so maybe Doxygen has a problem with this syntactic way of doing things. You could probably turn this around a bit to get a good public inheritance or a real composition.
If you want to know more about private and protected inheritance : http://www.parashift.com/c++-faq-lite/private-inheritance.html
Hope it helps !
|
2,687,448 | 2,687,548 | GDB doesnt like my typedef | It seems that the following is to deep for the debugger in Qt even though the program uses it without problem
typedef QMap <int, QStringList> day2FileNameType;
typedef QMap <int, day2FileNameType> month2day2FileNameType;
typedef QMap <int, month2day2FileNameType> year2month2day2FileNameType;
year2month2day2FileNameType y2m2d2f;
now the first 2 typeDefs work okay with the debugger but the third one
retrieving data for watch view (over 100 pending request)
Is it wrong for me to try and use such a typedef as year2month2day2FileNameType?
| I don't even use QT (although I do use gdb), but if you google 'gdb typdef', you get A LOT of hits like this one:
http://qtcreator.blogspot.com/2009/07/gdb-typedef-bug-update.html
So if what you say is true, that the program, unchanged, runs when you use the same structure minus the typdefs, I would assume that this is, in fact, a bug. Maybe this one (or something similar) applies to your code:
http://osdir.com/ml/gdb.bugs.discuss/2004-09/msg00035.html
|
2,687,475 | 2,687,498 | Potential problems porting to different architectures | I'm writing a Linux program that currently compiles and works fine on x86 and x86_64, and now I'm wondering if there's anything special I'll need to do to make it work on other architectures.
What I've heard is that for cross platform code I should:
Don't assume anything about the size of a pointer, int or size_t
Don't make assumptions about byte order (I don't do any bit shifting -- I assume gcc will optimize my power of two multiplication/division for me)
Don't use assembly blocks (obvious)
Make sure your libraries work (I'm using SQLite, libcurl and Boost, which all seem pretty cross-platform)
Is there anything else I need to worry about? I'm not currently targeting any other architectures, but I expect to support ARM at some point, and I figure I might as well make it work on any architecture if I can.
Also, regarding my second point about byte order, do I need to do anything special with text input? I read files with getline(), so it seems like that should be done automatically as well.
| In my experience, once code works well on a couple architectures, it will port more easily to a third one. Input shouldn't be an issue. Structure alignment may be an issue if you do anything where alignment is an issue.
Pay attention to anything that might be platform-dependent: relying on bitfields being aligned the same way, assuming variables are a particular size, etc. If your code is relatively abstract from the hardware, you will likely encounter few problems. If you are doing something with something like networking code, you will have to make sure you align with network byte order properly.
I have ported device drivers from PPC to x86, and then to x86_64; in a few thousand lines, there were maybe a couple changes, primarily related to structure and integer ordering.
The only way to know for sure is to try it, of course.
|
2,687,537 | 2,688,435 | JSON_Spirit: mapping value.type() back to the type? | You can display a Value's type like this:
cout << val.type() << end;
and it print a number.
How can I map this number back to the actual type?
besides peeking in the header file, of course, which reveals all...
enum Value_type {
obj_type,array_type,str_type,bool_type,int_type,real_type,null_type
};
| Nope, that seems to be the canonical way:
switch(v.type()) {
case obj_type: pp_obj(v, lev+1); break;
case array_type: pp_array(v, lev+1); break;
case str_type: pp<string>(v, lev+1); break;
case bool_type: pp<bool>(v, lev+1); break;
case int_type: pp<int>(v, lev+1); break;
case real_type: pp<double>(v, lev+1); break;
case null_type: pp_null(v, lev+1); break;
}
|
2,687,544 | 2,687,564 | Question about C++ inner class | HI,
In C++ inner class,
class A {
public:
void f1();
private:
void f2();
class B {
private void f3();
};
}
Does an inner class (B) has a pointer to its parent class (A)? (like it does in Java).
And can B calls its parent class public/private method (like it does in Java).
Thank you.
| No -- in C++, nesting classes only affects names and visibility, not the semantics of the class itself. As far as generated code goes, the nested class is no different from one that isn't nested.
All that's changed is the visibility and the name (e.g. if it's in a private: section of the outer class, it's not visible to the outside world, and if it's in a public: section, it's visible, but (of course) to name it you use outer_class::inner_class. It's still a completely separate class though -- just for example, you can create an instance of the inner class without creating any instance of the outer class.
Edit: Sorry, I missed part of your question. In C++ 0x, the inner class does have access to the the private parts of the outer class -- in essence, it's as if the outer class has declared the inner class as its friend, so private names are visible, but you still need to pass it something like a reference to an object of the outer class before it can invoke any non-static member functions of the outer class.
Although this isn't supposed to be the case yet, I believe most compilers implement this particular part already.
|
2,687,638 | 2,687,663 | Change character automatically whilst being input in c++? | I'm having trouble working this out. Basically my program has a standard input, I want to modify this so if the user enters a space it automatically replaces it with a / whilst they're typing. I have no idea how i'd even go about doing this or if it is even possible so I am grateful for any help either way.
| You would need to turn off echoing of the characters typed and then echo them yourself after validating them, replacing characters as necessary. There are different ways to do that for different operating systems (e.g. Linux vs. Windows), and even more unfortunately, that can mean taking control of the entire screen just for this simple function since the backspace/delete key would need to be handled properly (even over multiple lines if necessary). In short, you're taking control away from the user while making yourself responsible for the common functionality that a user would expect, which makes things rather difficult because you can't know how certain terminals behave, not to mention issues with locales. It's easier just to replace the characters yourself after the input is received or issue an error message, depending on your purpose and specific use-case.
Edit: PDCurses is cross-platform, so you might try that if you're still interested. It's easier than coding for specific platforms.
|
2,687,701 | 2,687,722 | How should I initialize a boost::array? | I am trying to understand the boost array. The code can be read easily from author's site.
In the design rationale, author (Nicolai M. Josuttis) mentioned that the following two types of initialization is possible.
boost::array<int,4> a = { { 1, 2, 3 } }; // Line 1
boost::array<int,4> a = { 1, 2, 3 }; // Line 2
In my experiment with g++ (version 4.1.2) Line 1 is working but Line 2 is not.
(Line 2 yields the following:
warning: missing braces around initializer for 'int [4]'
warning: missing initializer for member 'boost::array<int, 4ul>::elems'
)
Nevertheless, my main question is, how Line 1 is working? I tried to write a class similar to array.hpp and use statement like Line 1, but that did not work :-(. The error is
typedef array< unsigned int, 10 > MyArray;
MyArray b = { { 1, 2, 3 } }; // Line 74
array_test.cpp:74: error: in C++98 'b' must be initialized by constructor, not by '{...}'
array_test.cpp:74: error: no matching function for call to 'array<unsigned int, 10u>::array(<brace-enclosed initializer list>)'
array.h:16: note: candidates are: array<unsigned int, 10u>::array()
array.h:16: note: array<unsigned int, 10u>::array(const array<unsigned int, 10u>&)
Can somebody explain me? Is there some boost specific thing happening in Line 1 that I need to be aware of?
| this is a regular brace initialization list:
Boost array is defined like this:
struct array { T elems[N]; };
inner brace is for elems array initialization, outear brace is for struct initialization.
If you provide your own constructor, you no longer have plain old datatype any cannot initialize using brace
notice that you can go without outer brace, but you will get a warning
|
2,687,790 | 2,687,845 | How to accomplish covariant return types when returning a shared_ptr? | using namespace boost;
class A {};
class B : public A {};
class X {
virtual shared_ptr<A> foo();
};
class Y : public X {
virtual shared_ptr<B> foo();
};
The return types aren't covariant (nor are they, therefore, legal), but they would be if I was using raw pointers instead. What's the commonly accepted idiom to work around this, if there is one?
| I think that a solution is fundamentally impossible because covariance depends on pointer arithmetic which is incompatible with smart pointers.
When Y::foo returns shared_ptr<B> to a dynamic caller, it must be cast to shared_ptr<A> before use. In your case, a B* can (probably) simply be reinterpreted as an A*, but for multiple inheritance, you would need some magic to tell C++ about static_cast<A*>(shared_ptr<B>::get()).
|
2,687,849 | 2,687,936 | How to prevent anyone from stealing my shared_ptr? | So, I use boost::shared_ptr for all the various reference-counting benefits it provides -- reference counting for starters, obviously, but also the ability to copy, assign, and therefore store in STL Containers.
The problem is, if I pass it to just one "malicious" function or object, the object can save the ptr and then I'll never be able to de-allocate it without the foreign function or object nicely relinquishing its ownership.
Ultimately, I try to keep object ownership explicit. I accomplish this by having the owner keep the only shared_ptr to the object, and "guest" objects only store weak_ptrs to the object.
I really don't want the "shared" part of shared_ptr, but I'm required to use shared_ptr in order to make weak_ptrs. I want to use scoped_ptr, but it's extremely limited since you can't copy it. You can't store it in a container, you can't lend out weak_ptrs from it, and you can't transfer ownership to a new manager.
What's the solution?
| It's good enough to use weak_ptr for guest objects, as you described in question. Otherwise you will have a problem with dead pointers.
I would consider to do application rearchitect to remove "malicious" functions/objects or at least fix their behavior.
|
2,687,867 | 2,687,917 | Win32 API prevent standby | What is the Win32 api function that prevents the system from going into standby?
Some programs use it, which is pretty annoying in my opinion.
I know there's a couple of WM_SYSCOMMAND messages you can trap to prevent the screensaver from coming on..
| SetThreadExecutionState. There's no Get and it doesn't take a thread handle. Done.
|
2,687,967 | 2,688,010 | ISO C++ forbids declaration of 'Stack" with no type | I have setup the following header file to create a Stack which uses an Array. I get the following at line 7:
error: ISO C++ forbids declaration of 'Stack" with no type.
I thought the type was the input value. Appreciate your help. Thank you.
#ifndef ARRAYSTACKER_H_INCLUDED
#define ARRAYSTACKER_H_INCLUDED
// ArrayStacker.h: header file
class ArrayStack {
int MaxSize;
int EmptyStack;
int top;
int* items;
public:
Stacker(int sizeIn);
~Stacker();
void push(int intIn);
int pop();
int peekIn();
int empty();
int full();
};
#endif // ARRAYSTACKER_H_INCLUDED
| The error: ISO C++ forbids declaration of "identifier" with no type. error indicates that the declared type of identifier or identifier, itself, is a type for which the declaration has not been found.
For example, if you wrote the following in your code:
ArrayStack Stack;
The line above would give you such an error if you had failed to include the header in which "ArrayStack" is defined. You would also get such an error, if you accidentally used Stack instead of ArrayStack (e.g. when declaring a variable or when using it as function's return-type, etc.). I should also point out that your header has a fairly obvious error that you probably want to correct; a class's constructor and destructor must match the name of the class. The compiler is going to be confused, because when it sees "Stacker", it is going to interpret it as a function named "Stacker" where you simply forgot to give it a return-type (it won't realize that you actually meant for that to be the constructor, and simply mispelled it).
|
2,687,991 | 2,704,631 | Type problem when including tuple | I'm using Visual Studio 2008 with Feature Pack 1.
I have a typedef like this typedef std::tr1::tuple<std::string, std::string, int> tileInfo
with a function like this const tileInfo& GetTile( int x, int y ) const.
In the implementation file the function has the exact same signature (with the added class name qualifier) and I am getting a redefinition: different type modifiers error. It seems to be looking for an int& instead of a tileInfo&
When I mouse over the type of the function in the header, i.e. tileInfo& it brings up a little bar saying static const int tileInfo. I think this may be the problem, but I'm not sure what to do. It leads me to believe that the compiler thinks std::tr1::tuple<std::string, std::string, int> is a static const int.
Any help is appreciated, thanks.
P.S. Here is an example emulating the same situation, just compacted to the minimum.
#include <tuple>
class Blah {
public:
typedef std::tr1::tuple<std::string, std::string, int> tileInfo;
tileInfo& GetTile( int x, int y ); // When you mouse over tileInfo in this line, it says static const int
...
};
| It seems that when using the typedef as a return type or a local variable, even within the class, I had to qualify it with the class name as well. For example the GetTile signature in the header should have been TileMap::tileInfo& GetTile( int x, int y ); I thought that you didn't need to do this when the function is in the class with the typedef.
|
2,688,043 | 2,688,095 | Call/Return feature of classic C++(C with Classes), what modern languages have it? | On page 57 of The Design and Evolution of C++, Dr. Stroustrup talks about a feature that was initially part of C with Classes, but it isn't part of modern C++(standard C++). The feature is called call/return. This is an example:
class myclass
{
call() { /* do something before each call to a function. */ }
return() { /* do something else after each call to a function. */ }
...
};
I find this feature very interesting. Does any modern language have this particular feature?
| The modern C++ equivalent would be a sentry object: construct it at the beginning of a function, with its constructor implementing call(), and upon return (or abnormal exit), its destructor implements return().
|
2,688,096 | 2,688,190 | How to Set ActiveX Control name and link on the install window of Internet Explorer? | I created a ActiveX control using ATL, already package it with signature.
I want to use it on the webpage, but at the install window the name is MyActiveX.cab with no link. the MyActiveX.cab name can be changed by modifying the html page's tag codebase attribute. but the name is still format like "XXX.cab" with no hyperlink.
I find a activex control from chinese website has its own name and link:
and its object tags are nothing different:
<object ID="CMBPB_OCX"
CODEBASE="http://szdl.cmbchina.com/download/PB/pb50.cab#version=5,3,1,1"
classid="clsid:F2EB8999-766E-4BF6-AAAD-188D398C0D0B" width="0" height="0">
</object>
(source: microsoft.com)
the pic was taken from MSDN Pages, it has link.
Really want to know how to Set the activex control name?
I try to get help from How to Set ActiveX Control Name, but still get stuck.
I Signed the cab file and the activex dll file both, and don't know how to put the name and hyperlink in that window.
| Did you sign both control and CAB file?
It looks like you didn't sign the CAB file. The installation dialog shows info from the CAB file signature. Or maybe signature is invalid...
|
2,688,117 | 2,688,209 | C# style Action<T>, Func<T,T>, etc in C++0x | C# has generic function types such as Action<T> or Func<T,U,V,...>
With the advent of C++0x and the ability to have template typedef's and variadic template parameters, it seems this should be possible.
The obvious solution to me would be this:
template <typename T>
using Action<T> = void (*)(T);
however, this does not accommodate for functors or C++0x lambdas, and beyond that, does not compile with the error "expected unqualified-id before 'using'"
My next attempt was to perhaps use boost::function:
template <typename T>
using Action<T> = boost::function<void (T)>;
This doesn't compile either, for the same reason.
My only other idea would be STL style template arguments:
template <typename T, typename Action>
void foo(T value, Action f) {
f(value);
}
But this doesn't provide a strongly typed solution, and is only relevant inside the templated function.
Now, I will be the first to admit that I am not the C++ wiz I prefer to think I am, so it's very possible there is an obvious solution I'm not seeing.
Is it possible to have C# style generic function types in C++?
| I think the syntax should be like this:
template <typename T>
using Action = void (*)(T);
I couldn't get that to compile either, though (g++ v4.3.2).
The general STL style function template is not strongly typed in the strictest sense, but it is type safe in the sense that the compiler will ensure that the template is only instantiated for types that fulfill all the requirements of the function. Specifically it will be a compiler error if the Action is not callable with one parameter of type T. This a very flexible approach since it doesn't matter if Action is instantiated to be a function or some class that implements operator().
The old non-C++0x workaround for the missing templated typedef would be to use a templated struct with a nested typedef:
template <typename T>
struct Action {
typedef boost::function<void (T)> type;
};
template <typename T>
void foo(T value, typename Action<T>::type f) {
f(value);
}
|
2,688,283 | 2,688,295 | User input... How to check for ENTER key | I have a section of code where the user enters input from the keyboard. I want to do something when ENTER is pressed. I am checking for '\n' but it's not working. How do you check if the user pressed the ENTER key?
if( shuffle == false ){
int i=0;
string line;
while( i<20){
cout << "Playing: ";
songs[i]->printSong();
cout << "Press ENTER to stop or play next song: ";
getline(cin, line);
if( line.compare("\n") == 0 ){
i++;
}
}
}
| getline returns only when an Enter (or Return, it can be marked either way depending on your keyboard) is hit, so there's no need to check further for that -- do you want to check something else, maybe, such as whether the user entered something else before the Enter?
|
2,688,364 | 2,688,450 | C++ function overloading and dynamic binding compile problem |
Possible Duplicates:
C++ method only visible when object cast to base class?!
Why does an overridden function in the derived class hide other overloads of the base class?
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo(void) const { cout << "A::foo(void)" << endl; }
virtual void foo(int i) const { cout << i << endl; }
virtual ~A() {}
};
class B : public A
{
public:
void foo(int i) const { this->foo(); cout << i << endl; }
};
class C : public B
{
public:
void foo(void) const { cout << "C::foo(void)" << endl; }
};
int main(int argc, char ** argv)
{
C test;
test.foo(45);
return 0;
}
The above code does not compile with:
$>g++ test.cpp -o test.exe
test.cpp: In member function 'virtual void B::foo(int) const':
test.cpp:17: error: no matching function for call to 'B::foo() const'
test.cpp:17: note: candidates are: virtual void B::foo(int) const
test.cpp: In function 'int main(int, char**)':
test.cpp:31: error: no matching function for call to 'C::foo(int)'
test.cpp:23: note: candidates are: virtual void C::foo() const
It compiles if method "foo(void)" is changed to "goo(void)". Why is this so? Is it possible to compile the code without changing the method name of "foo(void)"?
Thanks.
| The problem is, that inheritance is not carried over different namespaces. So to make it compile, you have to tell the compiler with the using directive:
class B : public A
{
public:
using A::foo;
void foo(int i) const { this->foo(); cout << i << endl; }
};
class C : public A
{
public:
using B::foo;
void foo(void) const { cout << "C::foo(void)" << endl; }
};
|
2,688,491 | 2,688,552 | Efficiency of manually written loops vs operator overloads | in the program I'm working on I have 3-element arrays, which I use as mathematical vectors for all intents and purposes.
Through the course of writing my code, I was tempted to just roll my own Vector class with simple arithmetic overloads (+, -, * /) so I can simplify statements like:
// old:
for (int i = 0; i < 3; i++)
r[i] = r1[i] - r2[i];
// new:
r = r1 - r2;
Which should be more or less identical in generated code. But when it comes to more complicated things, could this really impact my performance heavily? One example that I have in my code is this:
Manually written version:
for (int j = 0; j < 3; j++)
{
p.vel[j] = p.oldVel[j] + (p.oldAcc[j] + p.acc[j]) * dt2 + (p.oldJerk[j] - p.jerk[j]) * dt12;
p.pos[j] = p.oldPos[j] + (p.oldVel[j] + p.vel[j]) * dt2 + (p.oldAcc[j] - p.acc[j]) * dt12;
}
Using the Vector class with operator overloads:
p.vel = p.oldVel + (p.oldAcc + p.acc) * dt2 + (p.oldJerk - p.jerk) * dt12;
p.pos = p.oldPos + (p.oldVel + p.vel) * dt2 + (p.oldAcc - p.acc) * dt12;
I am attempting to optimize my code for speed, since this sort of code runs inside of inner loops. Will using the overloaded operators for these things affect performance? I'm doing some numerical integration of a system of n mutually gravitating bodies. These vector operations are extremely common so having this run fast is important.
Any insight would be appreciated, as would any idioms or tricks I'm unaware of.
| If the operations are inlined and optimised well by your compiler you shouldn't usually see any difference between writing the code well (using operators to make it readable and maintainable) and manually inlining everything.
Manual inlining also considerably increases the risk of bugs because you won't be re-using a single piece of well-tested code, you'll be writing the same code over and over. I would recommend writing the code with operators, and then if you can prove you can speed it up by manually inlining, duplicate the code and manually inline the second version. Then you can run the two variants of the code off against each other to prove (a) that the manual inlining is effective, and (b) that the readable and manually-inlined code both produce the same result.
Before you start manually inlining, though, there's an easy way for you to answer your question for yourself: Write a few simple test cases both ways, then execute a few million iterations and see which approach executes faster. This will teach you a lot about what's going on and give you a definite answer for your particular implementation and compiler that you will never get from the theoretical answers you'll receive here.
|
2,688,575 | 2,688,592 | C triple dereferencing |
Possible Duplicate:
Uses for multiple levels of pointer dereferences?
I have used functions with doubly dereferenced pointers (**var) to return values. However, I was recently asked a question to figure out a use-case where a triple dereferencing (***var) may be needed. I couldn't think of any practical scenario. Does anyone have any experience here?
| Three dimensional arrays.
|
2,688,642 | 2,689,113 | How to write a simple Lexer/Parser with antlr 2.7? | I have a complex grammar (in antlr 2.7) which I need to extend. Having never used antlr before, I wanted to write a very simple Lexer and Parser first.
I found a very good explanation for antlr3 and tried to adapt it:
header{
#include <iostream>
using namespace std;
}
options {
language="Cpp";
}
class P2 extends Parser;
/* This will be the entry point of our parser. */
eval
: additionExp
;
/* Addition and subtraction have the lowest precedence. */
additionExp
: multiplyExp
( "+" multiplyExp
| "-" multiplyExp
)*
;
/* Multiplication and addition have a higher precedence. */
multiplyExp
: atomExp
( "*" atomExp
| "/" atomExp
)*
;
/* An expression atom is the smallest part of an expression: a number. Or
when we encounter parenthesis, we're making a recursive call back to the
rule 'additionExp'. As you can see, an 'atomExp' has the highest precedence. */
atomExp
: Number
| "(" additionExp ")"
;
/* A number: can be an integer value, or a decimal value */
number
: ("0".."9")+ ("." ("0".."9")+)?
;
/* We're going to ignore all white space characters */
protected
ws
: (" " | "\t" | "\r" | "\n") { newline(); }
;
It does generate four files without errors: P2.cpp, P2.hpp, P2TokenTypes.hpp and P2TokenTypes.txt. But now what? How do I create a working programm with that? I tried to add these files to a VS2005-WinConsole-Project but it does not compile:
p2.cpp(277) : fatal error C1010:
unexpected end of file while looking
for precompiled header. Did you forget
to add '#include "stdafx.h"' to your
source?
| look at these examples, there are some C examples which should help you on the way.
BTW the error message comes from that you are compiling with precompiled headers so it wants the stdafx.h include at the start of your .cpp file, you can add this in the grammar in the header{ } section.
|
2,688,713 | 2,688,727 | Copy constructor demo (crashing...) | Here is the program...
class CopyCon
{
public:
char *name;
CopyCon()
{
name = new char;
}
CopyCon(const CopyCon &objCopyCon)
{
name = new char;
_tcscpy(name,objCopyCon.name);
}
~CopyCon()
{
if( name != NULL )
{
delete name;
name = NULL;
}
}
};
int main()
{
CopyCon objCopyCon1;
objCopyCon1.name = "Hai";
CopyCon objCopyCon2(objCopyCon1);
objCopyCon1.name = "Hello";
cout<<objCopyCon2.name<<endl;
return 0;
}
Once the code execution completes, when the destructor called, it crashes on 'delete' saying...
Debug Error!
Program: ...
HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990.
CRT detected that the application wrote to memory after end of heap buffer.
(Press Retry to debug the application)
Don't we have to clear the heap memory in destructor. What's wrong with this program? Pls someone help!
Copy constructor works perfectly as intended. But still... !?
| The problem is you are allocating only one char in the copy constructor.
In main you are assigning a 4-byte string (remember the null), but when you copy the object, you only allocate enough room for 1 byte.
What you probably want to do is change
name = new char;
to
name = new char[tcslen(objCopyCon.name) + 1];
And in the destructor:
delete name;
to
delete [] name;
Also:
You are assigning "Hai" and "Hello" to objCopyCon1.name which is hiding the memory allocated in the constructor. This memory can never be freed!
|
2,688,801 | 2,688,957 | Better name for CHAR_BIT? | I was just checking an answer and realized that CHAR_BIT isn't defined by headers as I'd expect, not even by #include <bitset>, on newer GCC.
Do I really have to #include <climits> just to get the "functionality" of CHAR_BIT?
| As you may know, whether or not an implementation wants to include other headers is unspecified. It's allowed, but not mandated. (§17.4.4.1) So you either have to be explicit or know your guarantees.
The only time a C++ header must include another is if it requires a definition in another. For example, <bitset> is required to include <cstddef> for std::size_t, as this is explicitly stated in the standard. (§23.3.5, for this example)
For a counter-example, consider <limits>. It may include <climits> and define the values for numeric_limits in terms of the macros within, and it often does since that's easiest for an implementation. But all the standard says is things like: "Equivalent to CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN, etc." but doesn't say it must to be implemented in terms of those, which means <climits> doesn't have to be included.
So the only way you can be guaranteed that a CHAR_BIT is defined is by including <climits> or some other header where it's explicitly stated it must include it. And as far as I can tell, none have to; an implementation is free to just hard-code the value everywhere it's needed, for example, or include <limits> and use std::numeric_limits<unsigned char>::digits (which is equivalent).
|
2,689,204 | 2,689,274 | C++ File I/O problem | I am trying to open a file which normally has content, for the purpose of testing i will like to initialize the program without the files being available/existing so then the program should create empty ones, but am having issues implementing it. This is my code originally
void loadFiles() {
fstream city;
city.open("city.txt", ios::in);
fstream latitude;
latitude.open("lat.txt", ios::in);
fstream longitude;
longitude.open("lon.txt", ios::in);
while(!city.eof()){
city >> cityName;
latitude >> lat;
longitude >> lon;
t.add(cityName, lat, lon);
}
city.close();
latitude.close();
longitude.close();
}
I have tried everything i can think of, ofstream, ifstream, adding ios::out all all its variations. Could anybody explain me what to do in order to fix the problem. Thanks!
| You have posted code for reading files, not creating empty ones - you need t expand your question in this regard. And what you have posted is not good code for reading. The eof() function detects end of file following a read, not before one - basically, you should almost never use it. Instead, you should test the success of each read:
while( (city >> cityName) && (latitude >> lat) && (longitude >> lon) {
t.add(cityName, lat, lon);
}
Also, if you want to create an input stream, why not do so explicitly using an ifstream object:
ifstream city( "city.txt" );
No need to mess around with ios flags. You should really test if the open worked too:
if ( ! city.is_open() ) {
throw "open failed" ; // or whatever
}
|
2,689,351 | 2,689,897 | Porting Symbian C++ to Android NDK | I've been given some Symbian C++ code to port over for use with the Android NDK.
The code has lots of Symbian specific code in it and I have very little experience of C++ so its not going very well.
The main thing that is slowing me down is trying to figure out the alternatives to use in normal C++ for the Symbian specific code.
At the minute the compiler is throwing out all sorts of errors for unrecognised types.
From my recent research these are the types that I believe are Symbian specific:
TInt, TBool, TDesc8, RSocket, TInetAddress, TBuf, HBufc,
RPointerArray
Changing TInt and TBool to int and bool respectively works in the compiler but I am unsure what to use for the other types?
Can anyone help me out with them? Especially TDesc, TBuf, HBuf and RPointerArray.
Also Symbian has a two phase contructor using
NewL
and
NewLc
But would changing this to a normal C++ constructor be ok?
Finally Symbian uses the clean up stack to help eliminate memory leaks I believe, would removing the clean up stack code be acceptable, I presume it should be replaced with try/catch statements?
| It would typically be a bad idea to try and port Symbian OS C++ to standard C++ without having a very good understanding of what the Symbian idioms do.
This could very well be one of these projects where the right thing to do is to rewrite most of the code pretty much from scratch. If you barely know the language you are targetting, there is little point in deluding yourself into thinking you won't make mistakes, waste time and throw away new code anyway. It's all part of learning.
The CleanupStack mechanism is meant to help you deal with anything that could go wrong, including power outage and out of memory conditions. Technically, these days, it is implemented as C++ exceptions but it covers more than the usual error cases standard C++ code normally handles.
Descriptors (TDesc, TBuf and HBuf all belong to the descriptor class hierarchy) and templates (arrays, queues, lists...) predate their equivalent in standard C++ while dealing with issues like the CleanupStack, coding standards, memory management and integrity...
A relevant plug if you want to learn about it: Quick Recipes On Symbian OS is a recent attempt at explaning it all in as few pages as possible.
You should also definitely look at the Foundation website to get started.
Classes prefixed by T are meant to be small enough by themselves that they can be allocated on the stack.
Descriptor classes suffixed by C are meant to be immutable (A mutable descriptor can usually be created from them, though).
HBufC is pretty much the only Symbian class prefixed by H. It should always be allocated on the Heap.
A method suffixed by C will add an object on the CleanupStack when it returns successfully (usually, it's the object it returns). It's up to the calling code to Pop that object.
Classes prefixed by R are meant to be allocated on the stack but manage their own heap-based resources. They usually have some kind of Close() method that needs to be called before their destructor.
A typical way to thing about the differences between a collection of objects and a collection of pointers to object is who owns the objects in the collection. Either the collection owns the objects when they are added and looses them when they are removed (and is therefore responsible for deleting each object it still contains when it is itself destroyed) or the collection doesn't transfer ownership and something else must ensure the objects it contains will stay valid during the collection's lifetime.
Another way to think about collections is about how much copying of objects you want to happen when you add/get objects to/from the collection.
Symbian descriptor and collection classes are meant to cover all these different ways of using memory and let you choose the one you need based on what you want to do.
It's certainly not easy to do it right but that's how this operating system works.
|
2,689,380 | 2,689,388 | Typedef C++, couldn't resolve its meaning | I read this typedef line in a C++ book, but I couldn't resolve its meaning:
typedef Shape* (*CreateShapeCallBack)();
Now, CreateShapeCallBack stands for what, any idea?
Thanks.
| It's the type of a pointer to a function that returns a pointer to a Shape and takes no parameters. You could use it like this:
Shape * Func() {
// do stuff - return Shape pointer
}
...
CreateShapeCallBack p = Func;
|
2,689,590 | 2,689,742 | Creating ostream manipulators for a specific class | I have a class that is derived from ostream:
class my_ostream: public std::ostream
{
// ...
}
I want to make a manipulator (for example do_something), that works specifically to this class, like this:
my_ostream s;
s << "some text" << do_something << "some more text";
I did the following:
std::ostream &do_something(std::ostream &os)
{
my_ostream *s = dynamic_cast<my_ostream*>(&os);
if (s != NULL)
{
// do something
}
return os;
}
This works, but is rather ugly. I tried the following:
my_ostream &do_something(my_ostream &s)
{
// do something
return s;
}
This doesn't work. I also tried another approach:
class my_ostream: public std::ostream
{
// ...
my_ostream &operator<<(const do_something & x)
{
// do something
return *this;
}
}
This still doesn't work.
| You need to add support for manipulators in your class:
#include<iostream>
class my_ostream : public std::ostream
{
public:
std::string prefix;
my_ostream():prefix("*"){}
// manipulator support here:
my_ostream& operator<<( my_ostream&(*f)(my_ostream&)){
f(*this);
return *this;
}
};
my_ostream& operator<<(my_ostream &st, const std::string &s){
std::cout << st.prefix << s;
return st;
}
// manipulator: clear prefix
my_ostream& noprefix(my_ostream &st){
st.prefix="";
}
int main(){
my_ostream s;
std::string str1("text");
std::string str2("text");
s << str1 << noprefix << str2;
}
|
2,689,642 | 2,689,668 | Why can I derived from a templated/generic class based on that type in C# / C++ | Title probably doesn't make a lot of sense, so I'll start with some code:
class Foo : public std::vector<Foo>
{
};
...
Foo f;
f.push_back( Foo() );
Why is this allowed by the compiler? My brain is melting at this stage, so can anyone explain whether there are any reasons you would want to do this? Unfortunately I've just seen a similar pattern in some production C# code and wondered why anyone would use this pattern.
|
can anyone explain whether there are any reasons you would want to do this?
Curiously recurring template pattern.
|
2,689,709 | 2,689,761 | Difference between std::result_of and decltype | I have some trouble understanding the need for std::result_of in C++0x. If I understood correctly, result_of is used to obtain the resulting type of invoking a function object with certain types of parameters. For example:
template <typename F, typename Arg>
typename std::result_of<F(Arg)>::type
invoke(F f, Arg a)
{
return f(a);
}
I don't really see the difference with the following code:
template <typename F, typename Arg>
auto invoke(F f, Arg a) -> decltype(f(a)) //uses the f parameter
{
return f(a);
}
or
template <typename F, typename Arg>
auto invoke(F f, Arg a) -> decltype(F()(a)); //"constructs" an F
{
return f(a);
}
The only problem I can see with these two solutions is that we need to either:
have an instance of the functor to use it in the expression passed to decltype.
know a defined constructor for the functor.
Am I right in thinking that the only difference between decltype and result_of is that the first one needs an expression whereas the second does not?
| result_of was introduced in Boost, and then included in TR1, and finally in C++0x. Therefore result_of has an advantage that is backward-compatible (with a suitable library).
decltype is an entirely new thing in C++0x, does not restrict only to return type of a function, and is a language feature.
Anyway, on gcc 4.5, result_of is implemented in terms of decltype:
template<typename _Signature>
class result_of;
template<typename _Functor, typename... _ArgTypes>
struct result_of<_Functor(_ArgTypes...)>
{
typedef
decltype( std::declval<_Functor>()(std::declval<_ArgTypes>()...) )
type;
};
|
2,689,860 | 2,689,875 | Why cant we create Object if constructor is in private section? | I want to know why cant we create object if the constructor is in private section. I know that if i make a method static i can call that method using
<classname> :: <methodname(...)>;
But why can't we create object is what I don't understand.
I also know if my method is not static then also I can call function by the following:
class A
{
A();
public:
void fun1();
void fun2();
void fun3();
};
int main()
{
A *obj =(A*)malloc(sizeof(A));
//Here we can't use new A() because constructor is in private
//but we can use malloc with it, but it will not call the constructor
//and hence it is harmful because object may not be in usable state.
obj->fun1();
obj->fun2();
obj->fun3();
}
So, my question is: why can't we create an object when constructor is private?
| Because it is not accessible to the program, that's what private means. If you declared a member function or variable private, you would not be able to access them either. Creating private constructors is actually a useful technique in C++, as it allows you to say that only specific classes can create instances of the type. For example:
class A {
A() {} // private ctor
friend class B;
};
class B {
public:
A * MakeA() {
return new A;
}
};
Only B can create A objects - this is useful when implementing the factory pattern.
|
2,689,963 | 2,690,246 | Container for database-like searches | I'm looking for some STL, boost, or similar container to use the same way indexes are used in databases to search for record using a query like this:
select * from table1 where field1 starting with 'X';
or
select * from table1 where field1 like 'X%';
I thought about using std::map, but I cannot because I need to search for fields that "start with" some text, and not those that are "equal to". Beside that, I need it to work on multiple fields (each "record" has 6 fields, for example), so I would need a separate std::map for each one.
I could create a sorted vector or list and use binary search (breaking the set in 2 in each step by reading the element in the middle and seeing if it's more or less than 'X'), but I wonder if there is some ready-made container I could use without reinventing the wheel?
| Boost.Multi-Index allows you to manage with several index and it implements the lower_bound as for std::set/map. You will need to select the index corresponding to the field and then do as if it was a map or a set.
Next follows a generic function that could be used to get a couple of iterators, the fist to the first item starting with a given prefix, the second the first item starting with the next prefix, i.e. the end of the search
template <typename SortedAssociateveContainer>
std::pair<typename SortedAssociateveContainer::iterator,
typename SortedAssociateveContainer::iterator>
starts_with(
SortedAssociateveContainer const& coll,
typename SortedAssociateveContainer::key_type const& k)
{
return make_pair(coll.lower_bound(k),
coll.lower_bound(next_prefix(k));
}
where
next_prefix gets the next prefix using lexicographic order based on the SortedAssociateveContainer comparator (of course this function needs more arguments to be completely generic, see the question).
The result of starts_with can be used on any range algorithm (see Boost.Range)
|
2,690,235 | 2,690,256 | c++ templates and inheritance | I'm experiencing some problems with breaking my code to reusable parts using templates and inheritance. I'd like to achieve that my tree class and avltree class use the same node class and that avltree class inherits some methods from the tree class and adds some specific ones. So I came up with the code below. Compiler throws an error in tree.h as marked below and I don't really know how to overcome this. Any help appreciated! :)
node.h:
#ifndef NODE_H
#define NODE_H
#include "tree.h"
template <class T>
class node
{
T data;
...
node()
...
friend class tree<T>;
};
#endif
tree.h
#ifndef DREVO_H
#define DREVO_H
#include "node.h"
template <class T>
class tree
{
public: //signatures
tree();
...
void insert(const T&);
private:
node<T> *root; //missing type specifier - int assumed. Note: C++ does not support default-int
};
//implementations
#endif
avl.h
#ifndef AVL_H
#define AVL_H
#include "tree.h"
#include "node.h"
template <class T>
class avl: public tree<T>
{
public: //specific
int findMin() const;
...
protected:
void rotateLeft(node<T> *)const;
private:
node<T> *root;
};
#endif
avl.cpp (I tried separating headers from implementation, it worked before I started to combine avl code with tree code)
#include "drevo"
#include "avl.h"
#include "vozlisce.h"
template class avl<int>; //I know that only avl with int can be used like this, but currently this is doesn't matter :)
//implementations
...
| Both tree.h and node.h try to include each other, the include guards will prevent one of them from seeing the other.
Instead of #include "tree.h" try forward declaring tree like:
template <class T>
class tree;
in node.h
EDIT: As sbi suggested in a comment, it makes more sense to forward declare tree in node.h than the other way around, since it's about granting tree access to node through a friend declaration.
|
2,690,245 | 2,690,585 | Proper use of "atomic directive" to lock STL container | I have a large number of sets of integers, which I have, in turn, put into a vector of pointers. I need to be able to update these sets of integers in parallel without causing a race condition. More specifically. I am using OpenMP's "parallel for" construct.
For dealing with shared resources, OpenMP offers a handy "atomic directive," which allows one to avoid a race condition on a specific piece of memory without using locks. It would be convenient if I could use the "atomic directive" to prevent simultaneous updating to my integer sets, however, I'm not sure whether this is possible.
Basically, I want to know whether the following code could lead to a race condition
vector< set<int>* > membershipDirectory(numSets, new set<int>);
#pragma omp for schedule(guided,expandChunksize)
for(int i=0; i<100; i++)
{
set<int>* sp = membershipDirectory[rand()];
#pragma omp atomic
sp->insert(45);
}
Note that I use a random integer for the index, because in my application, any thread might access any index (there is a random element in my larger application, but I need not go into details).
I have seen a similar example of this for incrementing an integer, but I'm not sure whether it works when working with a pointer to a container as in my case.
| After searching around, I found the OpenMP C and C++ API manual on openmp.org, and in section 2.6.4, the limitations of the atomic construct are described.
Basically, the atomic directive can only be used with the following operators:
Unary:
++, -- (prefix and postfix)
Binary:
+,-,*,/,^,&,|,<<,>>
So I will just use locks!
(In some situations critical sections might be preferable, but in my case locks will provide fine grained access to the shared resource, yielding better performance than a critical section.)
|
2,690,328 | 2,692,689 | Qt quncompress gzip data | I stumble upon a problem, and can't find a solution.
So what I want to do is uncompress data in qt, using qUncompress(QByteArray), send from www in gzip format. I used wireshark to determine that this is valid gzip stream, also tested with zip/rar and both can uncompress it.
Code so far, is like this:
static const char dat[40] = {
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xaa, 0x2e, 0x2e, 0x49, 0x2c, 0x29,
0x2d, 0xb6, 0x4a, 0x4b, 0xcc, 0x29, 0x4e, 0xad, 0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00,
0x2a, 0x63, 0x18, 0xc5, 0x0e, 0x00, 0x00, 0x00
};
//this data contains string: {status:false}, in gzip format
QByteArray data;
data.append( dat, sizeof(dat) );
unsigned int size = 14; //expected uncompresed size, reconstruct it BigEndianes
//prepand expected uncompressed size, last 4 byte in dat 0x0e = 14
QByteArray dataPlusSize;
dataPlusSize.append( (unsigned int)((size >> 24) & 0xFF));
dataPlusSize.append( (unsigned int)((size >> 16) & 0xFF));
dataPlusSize.append( (unsigned int)((size >> 8) & 0xFF));
dataPlusSize.append( (unsigned int)((size >> 0) & 0xFF));
QByteArray uncomp = qUncompress( dataPlusSize );
qDebug() << uncomp;
And uncompression fails with: qUncompress: Z_DATA_ERROR: Input data is corrupted.
AFAIK gzip consist of 10 byte header, DEFLATE peyload, 12 byte trailer ( 8 byte CRC32 + 4 byte ISIZE - uncompresed data size ).
Striping header and trailer should leave me with DEFLATE data stream, qUncompress yields same error.
I checked with data string compressed in PHP, like this:
$stringData = gzcompress( "{status:false}", 1);
and qUncompress uncompress that data.(I didn't see and gzip header though i.e. ID1 = 0x1f, ID2 = 0x8b )
I checked above code with debug, and error occurs at:
if (
#endif
((BITS(8) << 8) + (hold >> 8)) % 31) { //here is error, WHY? long unsigned int hold = 35615
strm->msg = (char *)"incorrect header check";
state->mode = BAD;
break;
}
inflate.c line 610.
I know that qUncompress is simply a wrapper to zlib, so I suppose it should handle gzip without any problem. Any comments are more then welcome.
Best regards
| You also forgot dataPlusSize.append(data);. However, that won't solve your problem. The problem is that while gzip and zlib have the same compressed data format, their headers and trailers are different. See: http://www.zlib.net/zlib_faq.html#faq18
qUncompress uses the zlib uncompress, so it can only handle the zlib format, not the gzip format. It would need to call the gzXXXX functions to handle the gzip format.
The reason that qUncompress can handle output from PHP's gzcompress is that gzcompress compresses the given string using the ZLIB data format. See: http://php.net/manual/en/function.gzcompress.php
As CiscoIPPhone mentioned, you'll need to write your own to functions to handle gzip data.
|
2,690,380 | 2,690,395 | Stack allocation fails and heap allocation succeeds!! Is it possible? | I have the following piece of snippet
Class Sample
{ Obj_Class1 o1;
Obj_Class2 o2;};
But the size of Obj_Class1 and Obj_Class2 is huge so that the compiler shows a warning "Consider moving some space to heap". I was asked to replace Obj_Class1 o1 with Obj_Class1* o1 = new Obj_Class1(); But I feel that there is no use of making this change as heap allocation will also fail if stack allocation fails. Am I correct? Or does it make sense to make this change ( other than suppressing the compiler warning ).
| It is very typical that the stack is smaller than the heap. They use different memory locations. The stack is typically about a megabyte in size (you can change it, but be careful) and is allocated per thread. The heap can consume gigabytes if needed.
|
2,690,435 | 2,690,453 | OBject access from different functions in VC++ | I have 3 function in my class B. These three function have to access member function of other class A.
I did this by creating object of class A in class B constructor and tried to access that object in functions of class B. But its showing error.
How can i assess the same object in these three functions. Where i have to create object of class A
B::B()
{
A a;
}
B:: function()
{
a.fun(); //fun belongs to class A
}
B:: function1()
{
a.fun1(); //fun1 belongs to class A
}
I am getting error, How can i implement the same where i can access object a in both function.
| You need to make a a member variable of class B like this:
class B
{
private:
A a;
// ...
}
That will make it available to all the member functions of B.
(Making it private isn't necessary - the decision to make it private, protected or public depends on whether you want to make it available only within B, within B and B's derived classes, or everywhere.)
|
2,690,473 | 2,690,501 | How do virtual destructors work? | I am using gcc. I am aware how the virtual destructors solve the problem when we destroy a derived class object pointed by a base class pointer. I want to know how do they work?
class A
{
public:
A(){cout<<"A constructor"<<endl;}
~A(){cout<<"A destructor"<<endl;}
};
class B:public A
{
public:
B(){cout<<"B constructor"<<endl;}
~B(){cout<<"B destructor"<<endl;}
};
int main()
{
A * a = new B();
delete a;
getch();
return 0;
}
When I change A's destructor to a virtual function, the problem is solved. What is the inner working for this. Why do I make A's destructor virtual. I want to know what happens to the vtable of A and B?
| The key thing you need to know is that not using a virtual destructor in the above code is undefined behavior and that's not what you want. Virtual destructors are like any other virtual functions - when you call delete the program will decide what destructor to call right in runtime and that solves your problem.
|
2,690,601 | 2,692,208 | C++ wrapper for C library | Recently I found a C library that I want to use in my C++ project.
This code is configured with global variables and writes it's output to memory pointed by static pointers.
When I execute my project I would like 2 instances of the C program to run: one with configuration A and one with configuration B. I can't afford to run my program twice, so I think there are 2 options:
Make a C++ wrapper: The problem here is that the wrapper-class should contain all global/static variables the C library has. Since the functions in the C library use those variables I will have to create very big argument-lists for those functions.
Copy-paste the C library: Here I'll have to adapt the name of every function and every variable inside the C library.
Which one is the fastest solution?
Are there other possibilities to run 2 instances of the same C source?
Thanks,
Max
| C++ -Wrapper
You get away easier by pasting "the entire library" - only slightly modfied - into a class.
// C
static char resultBuffer[42];
void ToResult(int x) { ... }
char const * GetResult() { return resultBuffer; }
becomes
// C++
class CMyImportantCLib
{
private:
char resultBuffer[42];
void ToResult(int x) { ... } // likely, no code changes at all
char const * GetResult() { return resultBuffer; }
} ;
There are mostly declarative changes (such as "killing" static and extern declarations). You would need to hunt down static variables inside the methods, though, and turn them into members as well
Separate Namespaces
That is an ugly solution, but might be enough for you:
// impMyLib.h
namespace A
{
#include "c-lib.h"
}
namespace B
{
#include "c-lib.h"
}
// impMyLib.cpp
namespace A
{
#include "c-lib.c"
}
namespace B
{
#include "c-lib.c"
}
If you are lucky, the optimizer/linker succeeds in folding the identical code. However, types in A:: and B:: are unrelated.
|
2,690,773 | 2,691,308 | Is it safe to spin on a volatile variable in user-mode threads? | I'm not quite sure if it's safe to spin on a volatile variable in user-mode threads, to implement a light-weight spin_lock, I looked at the tbb source code, tbb_machine.h:170,
//! Spin WHILE the value of the variable is equal to a given value
/** T and U should be comparable types. */
template<typename T, typename U>
void spin_wait_while_eq( const volatile T& location, U value ) {
atomic_backoff backoff;
while( location==value ) backoff.pause();
}
And there is no fences in atomic_backoff class as I can see. While from other user-mode spin_lock implementation, most of them use CAS (Compare and Swap).
| Tricky. I'd say that in theory, this code isn't safe. If there are no memory barriers then the data accesses you're guarding could be moved across the spinlock. However, this would only be done if the compiler inlined very aggressively, and could see a purpose in this reordering.
Perhaps Intel simply determined that this code works on all current compilers, and that even though a compiler could theoretically perform transformations that'd break this code, those transformations wouldn't speed up the program, and so compilers probably won't do it.
Another possibility is that this code is only used on compilers that implicitly implement memory barriers around volatile accesses. Microsoft's Visual C++ compiler (2005 and later) does this. Have you checked if this is wrapped in an #ifdef block or similar, applying this implementation only on compilers where volatile use memory barriers?
|
2,690,851 | 2,691,220 | What is "sentry object" in C++? | I answered this question, and Potatoswatter answered too as
The modern C++ equivalent would be a
sentry object: construct it at the
beginning of a function, with its
constructor implementing call(), and
upon return (or abnormal exit), its
destructor implements
I am not familiar with using sentry objects in C++.
I thought they were limited to input and output streams.
Could somebody explain to me about C++ sentry objects as well as how to use them as an around interceptor for one or more methods in a class ?
i.e. How to do this ?
Sentry objects are very similar
indeed. On the one hand they require
explicit instantiation (and being
passed this) but on the other hand you
can add to them so that they check not
only the invariants of the class but
some pre/post conditions for the
function at hand.
| Sentry object is a pattern, but I'm not sure which one of those below (maybe all).
C++ programs often heavily rely on knowledge when exactly an object (possibly of a user-defined class) is destroyed, i.e. when its destructor is called. This is not the case for languages with garbage collection.
This technique is used, for example, to embrace "Resource Acquisition Is Initialization" paradigm: you acquire resources when an object constructor is called, and the compiler automatically calls its destructor to free resources in both normal and abnormal (exceptional) situations (check this question).
Common places where you can utilize the knowledge of construction/destruction timing are
Blocks: a destructor for "stack-allocated" object is called at the end of the block
void function()
{ Class foo = Object(resource);
other_operations();
} // destructor for foo is called here
Function calls: "stack-allocation" also happens when you call a function
void function()
{ another_function ( Class(resource) );
// destructor for the unnamed object is called
// after another_function() returns (or throws)
other_operations();
}
Construction/Destruction of the containing object:
class Foo
{ Class sentry;
public: Foo()
{ // Constructor for sentry is called here
something();
}
public: ~Foo()
{
something();
} // destructor for sentry is called here
};
In STL there's a class called sentry (more exactly, istream::sentry), which implements the third pattern of those described above. So I think that is what some programmers refer to as "sentry object".
But in fact any of the above objects of class Class may be called "sentry object". They're "sentry" because they ensure that these elusive object destructors are not missed even if something throws an exception (so they are like guardians of the block/class, of sorts).
More sentry object examples are in that RAII question.
You can see a relation to aspect-oriented programming; these objects are something like "aspects", with cutpoints "at the beginning/ending of the enclosing block", "at construction/destruction of containing object" etc. But these "aspects" have to present in the code they aspectate. So they're less "aspective" compared to the original call/return functionality; instead, a sentry object should be inserted to each function of the class:
class X{
struct Sentry {
Sentry() { /* call() */}
~Sentry() { /* return() */};
};
void member_function()
{ Sentry();
/* operations */
}
void another_member_function()
{ Sentry();
/* operations */
}
};
|
2,691,591 | 2,691,978 | HRESULT exception not caught in VS 2008 | I've got a stange situation in visual studio 2008 C++. I work on code that was originally written for visual studio 2003, where everything works well. Now, ported to VS 2008, the exception handling, which unfortuantely exists widely in the code, does not work anymore. standard code example:
try
{
HRESULT hr = S_OK;
// do stuff...
if( FAILED( hr ) )
throw hr;
}
catch( HRESULT hr )
{
// error handling, but we never get here
}
catch( ... )
{
// ... not even here
}
Under VS 2008, no exception is encountered, but I get a crash somewhere else, indicating that the stack pointer must be screwed up. Did anybody come across this behaviour? Any help is appreciated.
| After starting the debugger, go to Debug / Exceptions, and select for which exceptions the debugger should stop when the exception is thrown.
|
2,691,611 | 2,691,657 | Destructors for C++ Interface-like classes | Starting to use PC-Lint on an existing code base (fear and trepidation).
One thing that it complains about is the following:
class IBatch
{
public:
virtual void StartBatch() =0;
virtual int CommitBatch() =0;
};
Which when another class derives from this to use it like an interface
base class 'IBatch' has no destructor
So, the question: when you create Interface classes like the above, do you always include a virtual destructor? Why? (is it a style or a coding error?)
EDIT: Should have said that I do not expect or want the user of IBatch to destruct, they are a consumer of a service only, through this interface to some external implementing class (if that would make a difference)
|
A base class destructor should be either public and virtual, or protected and nonvirtual.
(Herb Sutter, Guru of the Week #18: "Virtuality")
|
2,691,650 | 2,691,725 | Getting Logical address of my system using C++ & Linux | Please suggest how to get the IP address of my system (logical address) using C++ and Linux.
| "Logical Address" is not meaningful. You either want an interface address (the IP that hosts on the same local network as the machine see), or you want the publicly-facing Internet address (the IP address hosts will see when this machine connects to them). The IP addresses will only be the same if the machine is directly connected to the Internet, which often isn't true.
Second, Linux hosts can (and do) have multiple interfaces, so which interface is just as important. It might be routing related (in which case it depends on the destination), or it might use policy routing (which again: will depend on the actual traffic).
Third: Linux hosts may have multiple addresses. That is, the system administrator may bind multiple IP addresses to the interface, either by using sub-interfaces (e.g. ifconfig eth0:2 ...) or by simply adding the secondary addresses (e.g. ip addr add ip dev eth0).
That's why your best bet is to tell the user what you want to do, and ask the user to give you the right piece of information, or just try and make the connection, and rely on the system to do the Right Thing.
For the few cases where you actually need an IP address (for example, if you're implementing an FTP client), a specialized approach will be the correct approach (in the FTP client case: using the results of getsockname() on the control channel). Knowing exactly why you think you need the IP address (and what information you have) will help get you a better answer.
|
2,691,680 | 2,783,305 | Why does Visual Studio 2010 throw this error with Boost 1.42.0? | I'm trying to recompile application, that compiles fine with warning level 4 in visual studio 2005 and visual studio 2008.
Since the errors (look below) are coming from std:tr1, I'm thinking there's some conflict, but not sure how to fix. My first thought was to remove all references to boost, such as but then I get an error that it can't find format method.
So here's one of the errors: (not sure what it means)
Any ideas, suggestions, solutions?
Thanks!
EDIT: Right at the beginning I see a message: Unknown compiler version - please run the configure tests and report the results
EDIT2: Piece of code that I think causes this error: (changed to protect the innocent)
EDIT3: I updated the error message, i.e added more..however I get many more error messages such as this one..so there's a bigger problem/issue.
!m_someMap.insert( std::make_pair( "somestring", SomeClass::isTrue ) ).second
....
.....
inline bool isTrue ( const IDog & dog ) { return s.IsDogTrue(); }
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(197): error C2752: 'std::tr1::_Remove_reference<_Ty>' : more than one partial specialization matches the template argument list
1> with
1> [
1> _Ty=bool (__cdecl &)(const IDog &)
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtr1common(356): could be 'std::tr1::_Remove_reference<_Ty&&>'
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtr1common(350): or 'std::tr1::_Remove_reference<_Ty&>'
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(962) : see reference to class template instantiation 'std::tr1::remove_reference<_Ty>' being compiled
1> with
1> [
1> _Ty=bool (__cdecl &)(const IDog &)
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(26) : see reference to class template instantiation 'std::tr1::decay<_Ty>' being compiled
1> with
1> [
1> _Ty=bool (__cdecl &)(const IDog &)
1> ]
1> C:\(PATH)\...(915) : see reference to class template instantiation 'std::tr1::_Unrefwrap<_Type>' being compiled
1> with
1> [
1> _Type=bool (__cdecl &)(const IDog &)
1> ]
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(965): error C2528: 'abstract declarator' : pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(349): error C2528: 'type' : pointer to reference is illegal
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(967) : see reference to class template instantiation 'std::tr1::add_pointer<_Ty>' being compiled
1> with
1> [
1> _Ty=bool (__cdecl &)(const IDog &)
1> ]
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\type_traits(197): error C2752: 'std::tr1::_Remove_reference<_Ty>' : more than one partial specialization matches the template argument list
1> with
1> [
1> _Ty=bool (__cdecl &)(const char *,int,const char *,std::string &)
1> ]
| the problem is with visual studio 2010, or I should say that with additional templates that were added to visual studio 2010 tr1, so, std::make_pair, doesn't always work. changed to pair<> and all errors magically went away.
so, if you have template problems in VC2010 and using std:make_pair, change it to pair<> and specify template parameters.
|
2,692,065 | 2,692,105 | what does "throw;" outside a catch block do? | I just stumbled this code:
void somefunction()
{
throw;
}
and I wonder: what does it mean?
| The intent is probably that somefunction() is only ever called from inside some catch block. In that case, there would be an exception active when the throw; is executed, in which case the current exception is re-thrown, to be caught by the next outer handler that can handle that exception type.
If throw; is executed when an exception is not active, it calls terminate() (N4810, §[expr.throw]/4).
|
2,692,074 | 2,692,116 | Constructor initialising an array of subobjects? | Say I have several objects within a class, each of which needs constructing with a different value. I can write something like this:
class b
{
public:
b(int num)
{
// 1 for a.b1, and 2 for a.b2
}
};
class a
{
public:
b b1;
b b2;
a() : b1(1), b2(2)
{
}
};
However, is it possible to do the same thing if those multiple objects are stored in an array?
My first attempt at it doesn't compile:
class a
{
public:
b bb[2];
a() : bb[0](1), bb[1](2)
{
}
};
| You cannot do this directly; you need to initialize the array elements in the body of the constructor.
The elements of the array are default constructed before the body of the constructor is entered. Since your example class b is not default constructible (i.e., it has no constructor that can be called with zero parameters), you can't have an array of b as a member variable.
You can have an array of a type that is not default constructible in other contexts, when you can explicitly initialize the array.
|
2,692,139 | 2,692,523 | How do I get rid of these warnings? | This is really several questions, but anyway...
I'm working with a big project in XCode, relatively recently ported from MetroWorks (Yes, really) and there's a bunch of warnings that I want to get rid of. Every so often an IMPORTANT warning comes up, but I never look at them because there's too many garbage ones. So, if I can either figure out how to get XCode to stop giving the warning, or actually fix the problem, that would be great. Here are the warnings:
It claims that <map.h> is antiquated.
However, when I replace it with <map>
my files don't compile. Evidently,
there's something in map.h that isn't
in map...
this decimal constant is unsigned only in ISO C90
This is a large number being compared to an unsigned long. I have even cast it, with no effect.
enumeral mismatch in conditional expression: <anonymous enum> vs <anonymous enum>
This appears to be from a ?: operator. Possibly that the then and else branches don't evaluate to the same type? Except that in at least one case, it's
(matchVp == NULL ? noErr : dupFNErr)
And since those are both of type OSErr, which is mac defined... I'm not sure what's up. It also seems to come up when I have other pairs of mac constants...
multi-character character constant
This one is obvious. The problem is that I actually NEED multi-character constants...
-fwritable-strings not compatible with literal CF/NSString
I unchecked the "Strings are Read-Only" box in both the project and target settings... and it seems to have had no effect...
| Items in <map.h> are in the global namespace while items in <map> are in the std namespace. Most likely you were just referring directly to the global versions and when you switched to <map> you were no longer seeing them because they moved to std::. In source files add a using namespace std to move on quickly. In headers you'll need to qualify uses of map-related items with std::.
I think you'll need to qualify the literal constant value with a trailing UL so it knows the correct type of the literal.
Most likely the enums are in two separate OS defined anonymous enums. You can static_cast them to quiet the warning.
No idea on the multi-byte chars.
Can you disable -fwritable-strings? Can you refactor the code that needs to modify constant strings?
|
2,692,383 | 2,692,431 | Convert struct into bytes | How would you convert any struct into byte array on processors with little-endian?
| You can use a char* to access any type of object in C++, so:
struct S
{
int a;
int b;
// etc.
};
S my_s;
char* my_s_bytes = reinterpret_cast<char*>(&my_s);
// or, if you prefer static_cast:
char* my_s_bytes = static_cast<char*>(static_cast<void*>(&my_s));
(There is at least some debate over the correctness of the reinterpret_cast vs. the static_cast; in practice it doesn't really matter--both should yield the same result)
|
2,692,548 | 2,692,683 | Beginner C++ Question | I have followed the code example here
toupper c++ example
And implemented it in my own code as follows
void CharString::MakeUpper()
{
char* str[strlen(m_pString)];
int i=0;
str[strlen(m_pString)]=m_pString;
char* c;
while (str[i])
{
c=str[i];
putchar (toupper(c));
i++;
}
}
But this gives me the following compiler error
CharString.cpp: In member function 'void CharString::MakeUpper()':
CharString.cpp:276: error: invalid conversion from 'char*' to 'int'
CharString.cpp:276: error: initializing argument 1of 'int toupper(int)'
CharString.cpp: In member function 'void CharString::MakeLower()':
This is line 276
putchar (toupper(c));
I understand that toupper is looking for int as a parameter and returns an int also, is that the problem? If so how does the example work?
| I'm going to go with the assumption that m_pString is a C style string (char *). You're doing way more fiddling than you need to be doing.
void CharString::MakeUpper()
{
char* str = m_pString; // Since you're not modifying the string, there's no need to make a local copy, just get a pointer to the existing string.
while (*str) // You can use the string pointer as an iterator over the individual chars
{
putchar (toupper(*str)); // Dereference the pointer to get each char.
str++; // Move to the next char (you can merge this into the previous line if so desired, but there's no need.
}
}
In the example you cite, the reason it works is because of how the variables are declared.
int main ()
{
int i=0;
char str[]="Test String.\n"; // This is a compile time string literal, so it's ok to initialize the array with it. Also, it's an array of `char`s not `char*`s.
char c; // Note that this is also a `char`, not a `char *`
while (str[i])
{
c=str[i];
putchar (toupper(c));
i++;
}
return 0;
}
Because of the error-prone ways of using C strings, your best bet is std::string:
void CharString::MakeUpper()
{
string str(m_pString);
transform(str.begin(), str.end(), ostream_iterator<char>(cout), &toupper);
}
|
2,692,609 | 2,692,630 | C++ Macro is not replacing all values | I have the following 2 macros:
#define SCOPED_ENUM_HEADER(NAME) struct NAME{ enum _NAME{
#define SCOPED_ENUM_FOOTER(NAME) };}; typedef NAME::_NAME NAMEtype;
Only the first instance of NAME get replaced by the passed NAME. What's wrong with it?
Is is to be used in such a way:
SCOPED_ENUM_HEADER(LOGLEVEL)
UNSET,
FILE,
SCREEN
SCOPED_ENUM_FOOTER(LOGLEVEL)
| The problem is that NAME is not the same as _NAME; they are two totally separate identifiers.
If you want to add an underscore to the front of whatever the parameter NAME is, use the concatenation (##) operator:
_##NAME
You do need to be really careful with prepending an underscore, though. All identifiers beginning with an underscore followed by a capital letter are reserved to the implementation.
|
2,692,728 | 2,692,756 | How to randomize a sorted list? | Here's a strange question for you guys,
I have a nice sorted list that I wish to randomize. How would i go about doing that?
In my application, i have a function that returns a list of points that describe the outline of a discretized object. Due to the way the problem is solved, the function returns a nice ordered list. i have a second boundary described in math and want to determine if the two objects intersect each other. I simply itterate over the points and determine if any one point is inside the mathematical boundary.
The method works well but i want to increase speed by randomizing the point data. Since it is likely that that my mathematical boundary will be overlapped by a series of points that are right beside each other, i think it would make sense to check a randomized list rather than iterating over a nice sorted one (as it only takes a single hit to declare an intersection).
So, any ideas on how i would go about randomizing an ordered list?
| Use std::random_shuffle. If you want to implement the method yourself you should look at the Fisher-Yates shuffle.
|
2,692,736 | 2,692,962 | D operators that are not in C++ | Are there any operators in D that are not in C++?
| Here is a list of some D tokens
/=
.
..
...
&
&=
&&
|
|=
||
-
-=
--
+
+=
++
<
<=
<<
<<=
<>
<>=
>
>=
>>=
>>>=
>>
>>>
!
!=
!<>
!<>=
!<
!<=
!>
!>=
(
)
[
]
{
}
?
,
;
:
$
=
==
*
*=
%
%=
^
^=
~
~=
Those for example:
<>
<>=
!<>
!<>=
!<
!<=
!>
!>=
are special operators to compare floating point variables. You can find the description of them here http://www.digitalmars.com/d/1.0/expression.html
There are also the
is
!is
in
!in
typeof
operators.
|
2,692,768 | 2,692,785 | How can I implement a fast map having multiple keys? | I'm looking for a C++ associative map container type which I can perform multiple key lookups on. The map needs to have constant time lookups, but I don't care if it's ordered or unordered. It just needs to be fast.
For example, I want to store a bunch of std::vector objects in a map with an int and a void* as the lookup keys. Both the int and the void* must match for my vector to be retrieved.
Does such a container exist already? Or am I going to have to roll my own? If so, how could I implement it? I've been trying to store a boost::unordered_map inside another boost::unordered_map, but I have not had any success with this method, yet. Maybe I will continue Pershing this method if there is no simpler way.
| Constant look up requires a hash map. You can use a the boost::unordered_map (or tr1). The key would be the combined hash of the int and the void pointer.
|
2,692,889 | 2,692,923 | Template debugging in C++ | I have a template class that is:
template <class identifier,class registeredObject>
class FxPairRegistry : public FxRegistry<pair<identifier,registeredObject> >
{
public:
registeredObject GetEntry(identifier, FxBool assertValue = true);
void RegisterInOrder(const pair<identifier,registeredObject> &ob);
typedef typename std::vector<pair<identifier,registeredObject> >::iterator iter;
};
I then have:
template <class identifier,class registeredObject>
registeredObject FxPairRegistry<identifier,registeredObject>::GetEntry(identifier id, FxBool
assertValue)
{
for (iterator iter = mRegistryList.begin(); iter != mRegistryList.end(); iter++)
{
if ((*iter).first == id)
{
return (*iter).second;
}
}
}
But I get errors like:
error: missing template arguments before 'iter'
error: expected `;' before 'iter'
error: expected primary-expression before '!=' token
error: 'mRegistryList' was not declared in this scope
error: expected primary-expression before '++' token
error: expected primary-expression before ')' token
error: expected primary-expression before ')' token
error: missing template arguments before 'iter'
error: expected `;' before 'iter'
error: expected primary-expression before '!=' token
error: 'mRegistryList' was not declared in this scope
error: expected primary-expression before '++' token
I dont quite get what I am doing wrong, but I am rusty a bit for sure....
| It seems that here, you are typedef'ing a type called iter:
typedef typename std::vector<pair<identifier,registeredObject> >::iterator iter;
And then here:
iterator iter = mRegistryList.begin()
You are trying to define a variable called iter of type iterator, which (from the code you've shown) is not the name of any type that exists.
|
2,693,079 | 2,693,107 | Strange behavior of std::cout &operator<< | I came across something weird today, and I was wondering if any of you here could explain what's happening...
Here's a sample:
#include <iostream>
#include <cassert>
using namespace std;
#define REQUIRE_STRING(s) assert(s != 0)
#define REQUIRE_STRING_LEN(s, n) assert(s != 0 || n == 0)
class String {
public:
String(const char *str, size_t len) : __data(__construct(str, len)), __len(len) {}
~String() { __destroy(__data); }
const char *toString() const {
return const_cast<const char *>(__data);
}
String &toUpper() {
REQUIRE_STRING_LEN(__data, __len);
char *it = __data;
while(it < __data + __len) {
if(*it >= 'a' && *it <= 'z')
*it -= 32;
++it;
}
return *this;
}
String &toLower() {
REQUIRE_STRING_LEN(__data, __len);
char *it = __data;
while(it < __data + __len) {
if(*it >= 'A' && *it <= 'Z')
*it += 32;
++it;
}
return *this;
}
private:
char *__data;
size_t __len;
protected:
static char *__construct(const char *str, size_t len) {
REQUIRE_STRING_LEN(str, len);
char *data = new char[len];
std::copy(str, str + len, data);
return data;
}
static void __destroy(char *data) {
REQUIRE_STRING(data);
delete[] data;
}
};
int main() {
String s("Hello world!", __builtin_strlen("Hello world!"));
cout << s.toLower().toString() << endl;
cout << s.toUpper().toString() << endl;
cout << s.toLower().toString() << endl << s.toUpper().toString() << endl;
return 0;
}
Now, I had expected the output to be:
hello world!
HELLO WORLD!
hello world!
HELLO WORLD!
but instead I got this:
hello world!
HELLO WORLD!
hello world!
hello world!
I can't really understand why the second toUpper didn't have any effect.
| This is all because of your code
cout << s.toLower().toString() << endl << s.toUpper().toString() << endl;
and how toLower and toUpper are implemented. Following code should work as expected
cout << s.toLower().toString() << endl;
cout << s.toUpper().toString() << endl;
The issue is that toLower and toUpper don't create a new object but modify existing object. And when you call several modifying methods in the same block AND pass this object somewhere as argument, behavior is undefined.
EDIT: This is similar to popular question, what would be result of
int i = 5;
i += ++i + i++;
The correct answer here is the same: undefined. You can google for "sequence points" in C++ for deeper explanation.
|
2,693,147 | 2,693,369 | What's the difference between CArray<int, int> and CArray<int, int&>? | Same for CMap, CList, and pretty much everything that uses templates (I guess).
I find it a bit hard to understand when to use which. It's true that for classes and such, the <class, class&> form is usually what you want, but for basic types like int, float, etc., which form is preferred?
| I would say that if you don't really need something else, just use CArray<Type> and ARG_TYPE would be its default const TYPE&. Actually using Type& as ARG_TYPE is not a good idea. This theoretically allows CArray to modify the object/value you passed to the corresponding method. Of course CArray doesn't do anything like this but it is better to be on the safe side.
If you look at the source code that is available within MS VC, you'll see that ARG_TYPE is used in a few methods as type for argument that holds new value for some element(s) of the array such as
void SetAt(INT_PTR nIndex, ARG_TYPE newElement)
INT_PTR Add(ARG_TYPE newElement)
void SetAt(INT_PTR nIndex, ARG_TYPE newElement)
void InsertAt(INT_PTR nIndex, ARG_TYPE newElement, INT_PTR nCount = 1)
If you making your choice between Type and const Type&, then the only thing that is affected is how many times and which data would be copied. When value is passed by reference, only pointer to it is actually passed. This is really important for objects (additional call of copy constructor) but doesn't really matter for simple types. Of course you can try to save a few bytes by forcing copying char or short that is smaller than corresponding pointer (32/64 bit depending on platform) but I don't think that this really worth additional troubles. As I said before, I think that using default CArray<Type> is a good way unless you really have reasons to change it.
|
2,693,182 | 2,693,200 | DWORD to bytes using bitwise shift operators | I can't get it to work correctly.
#include <windows.h>
int main()
{
DWORD i = 6521;
BYTE first = i >> 32;
BYTE second = i >> 24;
BYTE third = i >> 16;
BYTE fourth = i >> 8;
i = (((DWORD)fourth) << 24) | (((DWORD)third) << 16) | (((DWORD)second) << 8) | first;
}
| BYTE first = (i >> 24) & 0xff;
BYTE second = (i >> 16) & 0xff;
BYTE third = (i >> 8) & 0xff;
BYTE fourth = i & 0xff ;
|
2,693,199 | 2,693,450 | Do Destructors Have Names According To The Standard? | Do class destructors have names in the pedantic sense according to the Standard?
Recall that constructors explicitly do not have names:
12.1.1 :
Constructors do not have names. A
special declarator syntax using an
optional sequence of
function-specifiers (7.1.2) followed
by the constructor’s class name
followed by a parameter list is used
to declare or define the constructor.
In such a declaration, optional
parentheses around the constructor
class name are ignored.
The Standard does not explicitly state that destructors do or do not have names, but there are many references to how to refer to and declare a destructor using special language, none of which refer directly to the destructor's name. The issue seems to be skirted around in various places:
12.4.1:
A special declarator syntax using an
optional function-specifier (7.1.2)
followed by ~ followed by the
destructor’s class name followed by an
empty parameter list is used to
declare the destructor in a class
definition.
5.2.4.1:
The use of a pseudo-destructor-name
after a dot . or arrow -> operator
represents the destructor for the
non-class type named by type-name. The
result shall only be used as the
operand for the function call operator
(), and the result of such a call has
type void. The only effect is the
evaluation of the postfix-expression
before the dot or arrow.
12.4.12 :
In an explicit destructor call, the
destructor name appears as a ~
followed by a type-name that names the
destructor’s class type. The
invocation of a destructor is subject
to the usual rules for member
functions (9.3), that is, if the
object is not of the destructor’s
class type and not of a class derived
from the destructor’s class type, the
program has undefined behavior (except
that invoking delete on a null pointer
has no effect).
This last case (12.4.12) seems to be the most direct reference to the destructor's name, but it still avoids saying that the destructor has a name, and is quite ambigious about this. 12.4.12 could be interpreted as "blah is the destructor's name" or as "destructors don't have names, but you can refer to the destructor as blah."
So, do destructors have names or not?
| First of all, the Standard is ambivalent on the use of "name", i think. First, it says (added the other forms of names below, as corrected by the C++0x draft)
A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1).
Then in parts of the Standard it uses "name" as if it would contain qualifier portions like foo::bar. And in other parts, it excludes such portions from a "name". One paragraph even says that a name prefixed by :: refers to a global name. But in our example, bar was prefixed by such a token, even though its intentionally not referring to a global name.
The construct in our example is not a name, i think, but rather two names, one qualifying the other. A destructor is referenced by the construct ~ class-name (see 3.4.5/3 and 3.4.3/6). Such a construct consists of a ~ token and a name, refering to the constructor's class. It's conventional to call it the destructor's "name" (just like the Standard at 3.4.3.1/2 talks about a "constructor name") - but pedantically, it isn't a name.
So, if you are pedantical, you would say that a destructor does not have an own name, but rather special mechanisms are used for referring to it. Likewise for constructors, special constructs are used to refer to them (otherwise, you couldn't declare a constructor out of class - the declaration has to refer to it!). And in C++0x using declarations have to be able to refer to them too, using the special constructs provided (see 3.4.3.1/2 for how you can refer to a constructor).
The destructor lookup is quite convoluted, and has quite a few bugs in the Standard. See this issue report for further details.
|
2,693,319 | 2,695,172 | QExplicitlySharedPointer and inheritance | What is the best way to use QExplicitlySharedPointer and inherited classes. I would like when the BaseClass exits on it's own to have a my d pointer be QExplicitlySharedPointer<BaseClassPrivate> and when I have a Derived class on top of this base class I'd like to have d be a QExplicitlySharedPointer<DerivedClassPrivate>.
I tried making DerivedClassPrivate inherit from BaseClassPrivate, and then make the d pointer protected and re-define the d-pointer in my derived class, but it seems now that I have two copies of the d-pointer both local to the class they are defined in... which is not what I want.
| What about this:
template< typename P = BaseClassPrivate >
class BaseClass
{
public:
void myBaseFunc() { d->myBaseFunc(); }
protected:
QExplicitlySharedDataPointer< P > d;
};
class DerivedClass : public BaseClass< DerivedClassPrivate >
{
public:
void myDerivedFunc() { d->myDerivedFunc(); }
};
|
2,693,374 | 2,698,232 | Apply algorithms considering a specific edge subset | I've got a huge graph with typed edge (i.e. edge with a type property). Say
typedef adjacency_list<vecS, vecS, vertex_prop, edge_prop> Graph;
The "type" of the edge is a member of edge_prop and has a value in {A,B,C,D},
I'd like to run the breadth first search algorithm considering only edges of type A or B.
How would you do that?
| Finally I think the boost::graph way to do this is to use boost:filtered_graph and demo for usage
"The filtered_graph class template is an adaptor that creates a filtered view of a graph. The predicate function objects determine which edges and vertices of the original graph will show up in the filtered graph."
Thus, you can provide a edge (or vertex) filtering functor base on a property_map.
In my case I'm using internal bundled properties. See Properties maps from bundled properties.
|
2,693,451 | 2,694,230 | problem with QDataStream & QDataStream::operator>> ( char *& s ) | QFile msnLogFile(item->data(Qt::UserRole).toString());
QDataStream logDataStream;
if(msnLogFile.exists()){
msnLogFile.open(QIODevice::ReadOnly);
logDataStream.setDevice(&msnLogFile);
QByteArray logBlock;
logDataStream >> logBlock;
}
This code doesnt work. The QByte that results is empty. Same thing if I use a char* . Oddely enough the same code works in another program. Im tying to find the difference between both. This works if i use int,uint, quint8, etc
| Assuming msnLogFile was not previously created using a QDataStream (if it was, then ignore this answer completely), you don't want to use the >> operator.
The reason is that when QDataStream is writing strings, it prepends the length of the string to the output bytes. This allows another QDataStream to read it back in with the correct length and get the same result. Hence, why int, qint8, etc work correctly; there's no prepended size, it's just the raw data.
If the contents of msnLogFile are strictly text, you need to pass the QIODevice::Text flag to open and use QIODevice::readLine() or QIODevice::readAll(), however if it's binary data you'd have to use QDataStream::readRawData() and read the data back out in the correct order with correct sizes.
|
2,693,558 | 2,693,823 | Prototyping Qt/C++ in Python | I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++.
Is this the right approach, and what tools (bindings, binding generators, IDE) should I use?
Ideally, everything should be available in the Ubuntu repositories so I wouldn't have to worry about incompatible or old versions and have everything set up with a simple aptitude install.
Is there any comprehensive documentation about this process or do I have to learn every single component, and if yes, which ones?
Right now I have multiple choices to make:
Qt Creator, because of the nice auto completion and Qt integration.
Eclipse, as it offers support for both C++ and Python.
Eric (haven't used it yet)
Vim
PySide as it's working with CMake and Boost.Python, so theoretically it will make replacing python code easier.
PyQt as it's more widely used (more support) and is available as a Debian package.
Edit: As I will have to deploy the program to various computers, the C++-solution would require 1-5 files (the program and some library files if I'm linking it statically), using Python I'd have to build PyQt/PySide/SIP/whatever on every platform and explain how to install Python and everything else.
|
I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++. Is this the right approach?
That depends on your goals. Having done both, I'd recommend you stay with Python wherever possible and reasonable. Although it takes a bit of discipline, it's very possible to write extremely large applications in Python. But, as you find hotspots and things that can be better handled in C++, you can certainly port relevant parts to C++.
Is there any comprehensive documentation about this process or do I have to learn every single component, and if yes, which ones?
Here's what I'd recommend for the various pieces:
EDITOR/IDE: Use any editor/IDE you're comfortable with, but I'd highly recommend one that supports refactoring. If you're comfortable with Eclipse, use it. If you want to mainly go the C++ route and you're not too familiar with any editors, you might be better off with QtCreator. Eric is an extremely good Python IDE with support for refactoring, unless you're going to be doing lots of C++, take a look at it. Even better, its source code is an example of good PyQt usage and practices.
PROCESS:
The quick summary:
Write your application in Python using PyQt
When identified as hotspots, convert decoupled Python classes to C++
Create bindings for those classes using SIP
Import the newly defined libraries in Python in place of their Python counterparts
Enjoy the speed boost
General details:
Write the application in Python using PyQt. Be careful to keep a good separation of concerns so that when you need to port pieces to C++ they will be separate from their dependencies. When you finally need to port something to C++, write it in C++/Qt and then create bindings for it using SIP. SIP has a good reference manual on the process, and you have all of PyQt as an example.
DEPLOYMENT:
C++ - For many applications the dependencies are sufficiently simple that it's not too difficult to create an installer using a tool like NullSoft's Installer or InnoSetup.
Python/PyQt - PyQt applications are a bit more difficult to install because of the dependency on Python and its dependence on the presence of the Qt libraries. One person documented his efforts on this post at ARSTechnica. py2exe works pretty well on Windows and should work fine. IME, freeze.py, which comes with the Python source, sometimes has problems determining which shared libraries are truly necessary and will sometimes end up creating a binary whose dependencies aren't present. Py2app can be made to work on Mac OS X.
But worse, however, is the PyQt/Qt licensing. If you are developing a commercial application, you need to have a commercial PyQt (and Qt) license and make sure to prevent the users from easily modifying the source or otherwise writing code against the PyQt/Qt API because of licensing restrictions. Because of that, the PyQt author created a tool called VendorId (although it has a Python license). Within VendorId is a tool called SIB that can be used to create an executable which depends only on the Python interpreter. But, if you're going to go this far, you might want to install a custom Python along with your application.
DISCLAIMER: I haven't used PySide at all, so I'm not sure how it compares to PyQt. Also, note the following warning on their website:
PySide is a work in progress and is not yet suited for application development requiring production-level stability.
But, on a good note, they intend, at least for the initial release to "maintain API compatibility with PyQt." So, aside from the C++ bindings, you could easily switch between the two later.
|
2,693,589 | 2,693,624 | array, I/O file and standard deviation (c++) | double s_deviation(double data[],int cnt, double mean)
{
int i;
double sum= 0;
double sdeviation;
double x;
//x = mean(billy,a_size);
for(i=0; i<cnt; i++)
{
sum += ((data[i]) - (mean));
}
sdeviation = sqrt(sum/((double)cnt));
return sdeviation;
}
When I cout the result from this function, it gave me NaN.
I tested the value of (mean) and data[i] using
return data[i] and return mean
they are valid.
when i replaced mean with an actual number, the operation returned a finite number.
but with mean as a variable, it produced NaH.
I can't see anything wrong with my code at the moment.
Again, I am sure mean, data are getting the right number based on those tests.
Thank you
| I'd guess that the value of mean is large relative to your data, so that some of the ((data[i]) - (mean)) values are negative, and so overall sum ends up being negative.
Then, when you try to compute sqrt(sum/((double)cnt)), you are taking the square root of a negative number, which results in complex number, which is not representable by a double.
However, the underlying problem is that your standard deviation algorithm is incorrect. You are supposed to sum the squares of the distances from the mean, not the distances themselves. Aside from making your computation correct, this also guarantees that sum is never negative, and so you can always get a real-valued square root.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.