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,514,158 | 2,514,199 | How to directly access a certain part of a text file in g++? | I have a text file containing a number of records. Each record is stored on a single line that is 100 characters long.
Let's say I want to directly access the nth record. I could do it using a for loop, reading in n lines until I get to the record.
But how could I access it directly?
| If the each line is exactly 100 characters long and the line ending is always \n (i.e. no \r\n stuff) and there's no blank lines and people won't use 1 tab for 8 spaces etc. you can use (with ifstream)
fin.seekg(101 * n, ios::beg); // Assume the initial record has n=0.
or (with FILE*)
fseek(f, 101 * n, SEEK_SET);
If you are unsure of any of the preconditions, use a loop.
|
2,514,278 | 2,575,579 | Scalable memory allocator experiences | I am currently evaluating a few of scalable memory allocators, namely nedmalloc and ptmalloc (both built on top of dlmalloc), as a replacement for default malloc / new because of significant contention seen in multithreaded environment. Their published performance seems to be good, however I would like to check what are experiences of other people who have really used them.
Were your performance goals satisfied?
Did you experience any unexpected or hard to solve issues (like heap corruption)?
If you have tried both ptmaalloc and nedmalloc, which of the two would you recommend? Why (ease of use, performance)?
Or perhaps you would recommend another scalable allocator (free with a permissible license preferred)?
| I have implemented NedMalloc into our application and I am quite content with the results. The contention I have seen before was gone, and the allocator was quite easy to plug in, even the general performance was very good, up to the point the overhead of memory allocations is out application is now close to unmesurable.
I did not try the ptmalloc, as I did not find a Windows ready version of it and I lost motivation once NedMalloc worked fine for me.
Besides of the two mentioned, I think it could be also interesting to try TCMalloc - it has some features which sound better then NedMalloc in theory (like very little overhead for small allocations, compared to 4 B header used by NedMalloc), however as it does not seem to have Windows port ready, it might also turn to be not exactly easy.
After a few weeks of using NedMalloc I was forced to abandon it, because its space overhead has proven to be too high for us. What hit us in particular was NedMalloc seems to be reclaiming the memory it is no longer used to the OS in a bad manner, keeping most of it still committed. For now I have replaced it with JEMalloc, which seems to be not that fast (it is still fast, but not as fast as NedMalloc was), but it is very robust in this manner and its scalability is also very good.
And after a few months of using JEMalloc I haved switched to TCMalloc. It took more effort to adapt it for Windows compared to the other ones, but its results (both performance and fragmentation) seem to be the best for us of what I have tested so far.
|
2,514,350 | 2,522,282 | C++ IDE for Linux with smart reference searching | Is there an IDE supporting C++ with REALLY smart searching of references? By 'reference' I mean usage of a class (or its member), variable, function in the whole Project or Workspace.
There's lots of IDE providing it. Some of them seem just to search for the text with same name giving lots of stuff, others are smarter and check the context (like class boundaries, namespace) but aren't accurate enough.
The best I've tried so far was Visual SlickEdit, but still there's more to wish.
class C1
{
int foo;
};
class C2
{
int foo;
};
For example in this situation when searching for C1::foo references I DON'T want C2::foo to be shown too.
So, is there an IDE that would be so smart?
Edit2
10x everybody for the answers so far.
I tried Eclipse, reference searching seems relatively good, but it takes it 20 minutes to index medium size project and 4 times of 5 it runs out of memory and crashes. I tried increasing it and some other advice and it got a little better, but still quite slow and annoying with these crashes.
I tried KDevelop3, but the feature mentioned in this question is not very advanced - seems to be just very advanced grep based text searching.
Edit4
KDevelop4 - I tried to make it work, but latest beta it's quite unusable for custom makefile projects, I was unable to do anything with it.
Edit5
I was surprised, but QT Creator did really well in my tests. It doesn't seem to create some tag/index files, but somehow manages to show very precisely the usage of variable/functions/classes. Unfortunately it seems to not work very correctly with templates, when following definitions of functions.
None of the mentioned IDEs could compete Visual SlickEdit in working with references, virtual functions, etc. QT Creator was the closest though, so I will choose it as an answer to my question.
| I think Qt-Creator can help you. There few new features added in new preview 2.0.
|
2,514,394 | 2,515,008 | Declare module name of classes for logging | I currently am adding some features to our logging-library. One of these is the possibility to declare a module-name for a class that automatically gets preprended to any log-messages writing from within that class. However, if no module-name is provided, nothing is prepended. Currently I am using a trait-class that has a static function that returns the name.
template< class T >
struct ModuleNameTrait {
static std::string Value() { return ""; }
};
template< >
struct ModuleNameTrait< Foo > {
static std::string Value() { return "Foo"; }
};
This class can be defined using a helper-macro. The drawback is, that the module-name has to be declared outside of the class. I would like this to be possible within the class. Also, I want to be able to remove all logging-code using a preprocessor directive. I know that using SFINAE one can check if a template argument has a certain member, but since other people, that are not as friendly with templates as I am, will have to maintain the code, I am looking for a much simpler solution. If there is none, I will stick with the traits approach.
Thanks in advance!
|
I would like this to be possible within the class.
This is not possible with your approach, explicit specializations have to be declared in the namespace of which the template is a member.
You don't say how the actual using code looks like, but you should be able to let name and overload resolution work for you (e.g. from a logging macro):
template<class T> const char* const name(const T&) { return ""; }
class X;
const char* const name(const X&) { return "X"; }
struct X {
// prints "X"
void f() { std::cout << name(*this) << std::endl; }
};
struct Y {
static const char* const name(const Y&) { return "Y"; }
// prints "Y"
void f() { std::cout << name(*this) << std::endl; }
};
struct Z {
// prints ""
void f() { std::cout << name(*this) << std::endl; }
};
If you want to define name() only in classes and not outside, there is of course no need for templates or overloads:
const char* const name() { return ""; }
struct X {
static const char* const name() { return "X"; }
// prints "X"
void f() { std::cout << name() << std::endl; }
};
struct Y {
// prints ""
void f() { std::cout << name() << std::endl; }
};
|
2,514,401 | 2,514,468 | Getting name and type of a struct field from its object | For example, I have a struct which is something like this:
struct Test
{
int i;
float f;
char ch[10];
};
And I have an object of this struct such as:
Test obj;
Now, I want to programmatically get the field names and type of obj. Is it possible?
This is C++ BTW.
| You are asking for Reflection in C++.
|
2,514,535 | 2,514,921 | How to get a filetype icon in Windows using C/C++? | I am looking for a C/C++ code which can get icon for a given filetype (eg. .doc, .pdf) on Windows. I need to make an application which will display a list of files and I need to have the file icons corresponding to those files.
I have seen C# code for the same but I have never worked with C# and don't think that I can use the same code for my use.
Please help!
| I've found this: http://msdn.microsoft.com/en-us/magazine/cc301425.aspx
So you basically call SHGetFileInfo with SHGFI_USEFILEATTRIBUTES and any file name/path (it doesn't matter if it doesn't exist), and it writes the filetype info to a SHFILEINFO.
|
2,514,539 | 2,514,554 | Is it a good idea to return " const char * " from a function? | Now I have a function that has to return a string. I saw a particular implementation where he returns a const char * from the function.
Something like this:
const char * GetSomeString()
{
........
return somestlstring.c_str();
}
SomeOtherFoo ()
{
const char * tmp = GetSomeString();
string s = tmp;
}
Now I felt there is something potentially wrong with this. Is my gut feel right? or Is this a perfectly safe code?
Kindly give me ur suggestions. I have a feeling return const char * this way might result in havoc..
Thanks,
Arjun
| Depending on what somestlstring is and what is being done there.
If it is a local variable you are returning a pointer into memory that is being released when GetSomeString completes, so it is a dangling pointer and an error.
It all boils down to the lifetime of somestlstring and the operations you perform on it. The pointer returned by .c_str() is guaranteed to be valid only up to the next mutating operation in the string. So if something changes somestlstring from the call to .c_str() and before s is constructed you will be in undefined behavior land.
|
2,515,261 | 2,515,285 | What are the definitions for LPARAM and WPARAM? | I know I'm being lazy here and I should trawl the header files for myself, but what are the actual types for LPARAM and WPARAM parameters? Are they pointers, or four byte ints? I'm doing some C# interop code and want to be sure I get it working on x64 systems.
| LPARAM is a typedef for LONG_PTR which is a long (signed 32-bit) on win32 and __int64 (signed 64-bit) on x86_64.
WPARAM is a typedef for UINT_PTR which is an unsigned int (unsigned 32-bit) on win32 and unsigned __int64 (unsigned 64-bit) on x86_64.
MSDN link
|
2,515,494 | 2,515,592 | Read in double type from txt file - C++ | I'm in the midst of a university project and have decided to implement a method that can accept information from a text file (in this instance called "locations.txt"). input from the text file will look like this:
London
345
456
Madrid
234
345
Beinjing
345
456
Frankfurt
456
567
The function looks like this currently (and you will notice I am missing the While condition to finish adding input when reaches end of text in locations.txt, i tried using eof but this didnt work?!). Also get function expects a char and so cant accept input thats a double which is what the latitude and longitude are defined as...
void populateList(){
ifstream inputFile;
inputFile.open ("locations.txt");
temp = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it
while(HASNT REACHED END OF TEXT FILE!!)
{
inputFile.getline(temp->nodeCityName, MAX_LENGTH);
// inputFile.get(temp->nodeLati, MAX_LENGTH);
// inputFile.get(temp->nodeLongi, MAX_LENGTH);
temp->Next = NULL; //set to NULL as when one is added it is currently the last in the list and so can not point to the next
if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node
start_ptr = temp;
}
else {
temp2 = start_ptr;
// We know this is not NULL - list not empty!
while (temp2->Next != NULL)
{
temp2 = temp2->Next; // Move to next link in chain until reach end of list
}
temp2->Next = temp;
}
}
inputFile.close();
}
Any help you can provide would be most useful. If I need to provide anymore detail I will do, I'm in a bustling canteen atm and concentrating is hard!!
| std::string city;
double lat, lgt;
while( (inputFile >> city ) && (inputFile >> lat) && (inputFile >> lgt ) ) {
// do something with values
}
|
2,515,527 | 2,515,582 | Use of iterators over array indices | I just wanted to know what is the main advantage of using the iterators over the array indices. I have googled but i am not getting the right answer.
| I presume you are talking about when using a vector, right?
The main advantage is that iterator code works for all stl containers, while the array indexing operator [] is only available for vectors and deques. This means you are free to change the underlying container if you need to without having to recode every loop. It also means you can put your iteration code in a template and it will work for any container, not just for deques and vectors (and arrays of course).
|
2,515,722 | 2,515,793 | Handling Complex Rules in GUI applications (C++ or C#) | Im working on a dialog box in which several rules must be satisfied before the OK button is enabled.
Currently any action on the page such as entering data or selecting an item from a drop down list (amongst other things) calls a single function called ProcessEvent() - this function handles all logic and either enables or disables the OK button.
My problem is I finding it difficult making the rules concise and understandable.
Some of the rules can be negated by another action on the dialog and I have now ended up with if else statements all over the place or which are difficult to read and follow & extend.
The code below is a simplification of the problem but demonstrates it well. How do I handle this problem better (If its Possible)
bool CWorkstation::ProcessEvent(void)
{
UpdateData();
CharCount = GetDlgItemInt(IDC_CharCount, NULL, FALSE); //get latest
if ( IsDlgButtonChecked(IDC_USEDBNAME))
{
if (!IsDlgButtonChecked(IDC_MAXDBNAME))
{
EnableNext(TRUE);
}
}
if (IsDlgButtonChecked(IDC_MAXDBNAME) && CharCount)
{
if (IsDlgButtonChecked(IDC_USEXMLNAME))
{
if ( PrefixName.IsEmpty() )
{
EnableNext(FALSE);
}
else
{
EnableNext(TRUE);
}
}
}
if (IsDlgButtonChecked(IDC_USEXMLNAME) && PrefixName.GetLength() > 1)
{
EnableNext(TRUE);
}
if ( IsDlgButtonChecked(IDC_WSAUTONAME) || IsDlgButtonChecked(IDC_RENAMEIFDUP))
{
// TRACE("IDC_WSAUTONAME is Checked\n");
if ( IsDlgButtonChecked(IDC_USEXMLNAME) && PrefixName.GetLength() > 1 )
{
if ( IsDlgButtonChecked(IDC_IDC_USESHORTNAME) )
{
EnableNext(TRUE);
}
else if ( IsDlgButtonChecked(IDC_USELONGNAME) )
{
EnableNext(TRUE);
}
else
{
EnableNext(FALSE);
}
}
if ( !IsDlgButtonChecked(IDC_USEPREFIX) )
{
if ( IsDlgButtonChecked(IDC_IDC_USESHORTNAME) || IsDlgButtonChecked(IDC_USELONGNAME) )
{
EnableNext(TRUE);
}
}
return false;
}
}
| I would split your if/else statements into multiple functions, and do an &= on the parameter you send to EnableNext. You should be calling EnableNext only once.
So, for example:
// in CWorkStation::ProcessEvent
bool enableNext = true; // start with true
enableNext &= Condition1(); // of course pick better names than Condition1
enableNext &= Condition2(); // this is just for an example
EnableNext(enableNext);
Where Condition1() might be:
bool Condition1()
{
return (IsDlgButtonChecked(IDC_USEDBNAME)
&& !IsDlgButtonChecked(IDC_MAXDBNAME));
}
And so on.
What's happening here is that the enableNext variable starts with true. Then, each &= you do means that if any of the ConditionX() functions returns false, enableNext will end up false. It will only be true at the end if ALL of the conditions are true.
|
2,515,922 | 2,518,224 | avoiding enums as interface identifiers c++ OOP | I'm working on a plugin framework using dynamic loaded shared libraries which is based on Eclipse's (and probally other's) extension-point model. All plugins share similar properties (name, id, version etc) and each plugin could in theory satisfy any extension-point. The actual plugin (ie Dll) handling is managed by another library, all I am doing really is managing collections of interfaces for the application.
I started by using an enum PluginType to distinguish the different interfaces, but I have quickly realised that using template functions made the code far cleaner and would leave the grunt work up to the compiler, rather than forcing me to use lots of switch {...} statements.
The only issue is where I need to specify like functionality for class members - most obvious example is the default plugin which provides a particular interface. A Settings class handles all settings, including the default plugin for an interface.
ie Skin newSkin = settings.GetDefault<ISkin>();
How do I store the default ISkin in a container without resorting to some other means of identifying the interface?
As I mentioned above, I currently use a std::map<PluginType, IPlugin> Settings::defaults member to achieve this (where IPlugin is an abstract base class which all plugins derive from. I can then dynamic_cast to the desired interface when required, but this really smells of bad design to me and introduces more harm than good I think.
would welcome any tips
edit: here's an example of the current use of default plugins
typedef boost::shared_ptr<ISkin> Skin;
typedef boost::shared_ptr<IPlugin> Plugin;
enum PluginType
{
skin,
...,
...
}
class Settings
{
public:
void SetDefault(const PluginType type, boost::shared_ptr<IPlugin> plugin) {
m_default[type] = plugin;
}
boost::shared_ptr<IPlugin> GetDefault(const PluginType type) {
return m_default[type];
}
private:
std::map<PluginType, boost::shared_ptr<IPlugin> m_default;
};
SkinManager::Initialize()
{
Plugin thedefault = g_settings.GetDefault(skinplugin);
Skin defaultskin = boost::dynamic_pointer_cast<ISkin>(theskin);
defaultskin->Initialize();
}
I would much rather call the getdefault as the following, with automatic casting to the derived class. However I need to specialize for every class type.
template<>
Skin Settings::GetDefault<ISkin>()
{
return boost::dynamic_pointer_cast<ISkin>(m_default(skin));
}
| What is the problem of the enum ? The lack of extensibility.
How to have extensibility and yet retain identification ? You need a full blown object, preferably with a specific type.
Basically you can get away with:
class IPluginId
{
public:
virtual IPluginId* clone() const = 0;
virtual ~IPluginId();
bool operator<(const IPluginId& rhs) const { return mId < rhs.mId; }
bool operator==(const IPluginId& rhs) const { return mId == rhs.mId; }
protected:
static size_t IdCount = 0;
IPluginId(size_t id): mId(id) {}
private:
size_t mId;
};
template <class Plugin>
class PluginId
{
public:
PluginId(): IPluginId(GetId()) {}
IPluginId* clone() const { return new PluginId(*this); }
private:
static size_t GetId() { static size_t MId = ++IdCount; return MId; }
};
Now, as for using, it would get:
// skin.h
class ISkin;
struct SkinId: PluginId<ISkin> {}; // Types can be forward declared
// Typedef cannot
class ISkin: public IPlugin { /**/ };
And now you can get use:
class Settings
{
public:
template <class Plugin>
void SetDefault(boost::shared_ptr<Plugin> p);
template <class Plugin>
boost::shared_ptr<Plugin> GetDefault(const PluginId<Plugin>& id);
private:
boost::shared_ptr<IPlugin> GetDefault(const IPluginId& id);
};
The template version is implemented in term of the non-template one and performs the downcast automatically. There is no way the pointer might be the wrong type because the compiler does the type checking, thus you get away with a static_cast :)
I know downcasting all over the place is kind of ugly, but here you just down_cast in one method GetDefault and it's type checked at compile time.
Even easier (let's generate the keys on the fly):
class Settings
{
public:
template <class Plugin>
void SetDefault(const boost::shared_ptr<Plugin>& p)
{
mPlugins[typeid(Plugin).name()] = p;
}
template <class Plugin>
boost::shared_ptr<Plugin> GetDefault() const
{
plugins_type::const_iterator it = mPlugins.find(typeid(Plugin).name());
if (it == mPlugins.end()) return boost::shared_ptr<Plugin>();
return shared_static_cast<Plugin>(it->second);
}
private:
typedef std::map<std::string, std::shared_ptr<IPlugin> > plugins_type;
plugins_type mPlugins;
};
However it's less safe than the first alternative, notably you can put anything there as long as it inherits from IPlugin, so you can put MySkin for example, and you won't be able to retrieve it through ISkin because typeid(T).name() will resolve to a different name.
|
2,515,966 | 2,515,988 | What is the point of STL? | I've been programming c++ for about a year now and when i'm looking about i see lots of references to STL.
Can some one please tell me what it does?
and the advantages and disadvantageous of it?
also what does it give me over the borlands VCL or MFC?
thanks
| It's the C++ standard library that gives you all sorts of very useful containers, strings, algorithms to manipulate them with etc.
The term 'STL' is outdated IMHO, what used to be the STL has become a large part of the standard library for C++.
If you are doing any serious C++ development, you will need to be familiar with this library and preferably the boost library. If you are not using it already, you're probably working at the wrong level of abstraction or you're constraining yourself to a small-ish subset of C++.
|
2,516,165 | 3,537,372 | Using time facets on universal_time | on boost, to create a time facet to format an specified time we use the folowing:
boost::local_time::local_time_facet* facet = new boost::local_time::local_time_facet("%Y%m%d %H:%M:%S.%f");
std::stringstream date_stream;
date_stream.imbue(std::locale(date_stream.getloc(), facet));
date_stream << boost::local_time::local_microsec_clock::local_time(boost::local_time::time_zone_ptr());
How do I do the same thing, but using an universal clock:
boost::posix_time::microsec_clock::universal_time()
Thanks
| I know that by now scooterman has either found the answer or doesn't care anymore (:D), but in the case that someone found this question while searching (like i did), here's the answer:
boost::posix_time::ptime time(microsec_clock::universal_time());
std::stringstream ss;
boost::date_time::time_facet *facetPtr
= new boost::date_time::time_facet("%a, %d %b %Y %H:%M:%S.%f GMT");
ss.imbue(std::locale(ss.getloc(), facetPtr));
ss << time;
//ss.str() contains the formatted time string
|
2,516,308 | 2,516,805 | Caller graph for overloaded operators in Visual Studio 2005 | Is is possible to get a callers graph for overloaded operators?
I have a simple struct with a natural ordering which I have represented by overloading the relational operators. Looking back through the code, it appears that I made a mistake in defining operator >. I had set the greater than to simply return the negation of operator < (this is not correct as this will mean that (val1 > val2) == true when val1 == val2).
Anyway before fixing this, I want to check where the > operator is called in the rest of the code to make sure there are no unintended consequences. This does not seem to be possible using the Visual Studio 2005 call browser. When I search for the function, it recognises where it is defined in the code, but lists there being no calls to or from that function, which is not the case.
Aside from searching through all instances of ">" in my project code do I have any other options?
This page - http://msdn.microsoft.com/en-us/magazine/cc163658.aspx#S3 - indicates that detecing operator calls is not something that was originally in VS2005, but I can't tell if this has changed.
|
Unless the class of which val1 and val2 are instances of has base classes that themselves implement operator> I suggest you remove your definition of operator> from the header and cpp files and recompile. This should give you a list of all calls to operator> guaranteed by the compiler.
Boost.Operators may help to avoid such errors in the future. It can automatically provide operator!= if you provide operator== e.g., the same goes for operator<=, operator> and operator>= if you provide operator<.
It is extremely hard to find all calls to overloaded operators in code due to templates and the precompiler: C++ IDE for Linux with smart reference searching
|
2,516,322 | 2,516,395 | How can I find out how much memory is physically installed in Windows? | I need to log information about how much RAM the user has. My first approach was to use GlobalMemoryStatusEx but that only gives me how much memory is available to windows, not how much is installed. I found this function GetPhysicallyInstalledSystemMemory but its only Vista and later. I need this to work on XP. Is there a fairly simple way of querying the SMBIOS information that GetPhysicallyInstalledSystemMemory was using or is there a registry value somewhere that I can find this out.
| EDIT: I'd use steelbytes' answer, but if you can't use WMI For some reason, you can do this:
I don't believe Windows versions prior to Vista track this information -- you'd have to do some system specific BIOS or Motherboard enumeration to find the true value prior to Vista. Your best bet is to call the new API, GetPhysicallyInstalledSystemMemory, and fail over to GlobalMemoryStatusEx for XP systems.
|
2,516,337 | 2,516,363 | What's the relationship between header files and library files in c++? | Why do we need to add both includes and libs to the compilation?
Why doesn't the libs wrap everything in it?
| A header file (usually) only contains declarations for classes and functions. The actual implementations are built from CPP files. You can then link against those implementations with only the header declarations available.
|
2,516,413 | 2,516,504 | Visual Studio Recompiles Project Every Time I Try to Run it | I have a Visual Studio 2005 solution. Every time I try to run the startup project (C++), the project gets build again, although I did not make any change.
How can I get the normal, sane behaviour, where projects get built only when needed?
How can I debug the problem further?
Thanks,
| On at least one occasion I've had files appear that had a last-write-time that was some time in the future. Presumably this occurred because either my computer's clock was wrong when the file was last written or the file came from another computer whose clock was wrong.
That can cause this problem, so check the timestamps on all your source files and check your computer's clock for the correct time.
Try this PowerShell command:
get-childitem . -Recurse | ? { $_.LastWriteTime -gt (Get-Date) }
|
2,516,631 | 2,516,650 | Cannot initialize non-const reference from convertible type | I cannot initialize a non-const reference to type T1 from a convertible type T2. However, I can with a const reference.
long l;
const long long &const_ref = l; // fine
long long &ref = l; // error: invalid initialization of reference of
// type 'long long int&' from expression of type
// 'long int'
Most problems I encountered were related to r-values that cannot be assigned to a non-const reference. This is not the case here -- can someone explain? Thanks.
| An integer promotion results in an rvalue. long can be promoted to a long long, and then it gets bound to a const reference. Just as if you had done:
typedef long long type;
const type& x = type(l); // temporary!
Contrarily an rvalue, as you know, cannot be bound to a non-const reference. (After all, there is no actual long long to refer to.)
|
2,516,866 | 2,517,302 | struct method linking | I'm updating some old code that has several POD structs that were getting zero'd out by memset (don't blame me...I didn't write this part). Part of the update changed some of them to classes that use private internal pointers that are now getting wiped out by the memset.
So I added a [non-virtual] reset() method to the various structs and refactored the code to call that instead.
One particular struct developed an "undefined reference to `blah::reset()'" error.
Changing it from a struct to a class fixed the error.
Calling nm on the .o file h, the mangled function names for that method look the same (whether it's a class or a struct).
I'm using g++ 4.4.1, on Ubuntu.
I hate the thought that this might be a compiler/linker bug, but I'm not sure what else it could be. Am I missing some fundamental difference between structs and classes? I thought the only meaningful ones were the public/private defaults and the way everyone thinks about them.
Update:
It actually depends on the way the it's declared:
typedef struct
{
...
void reset();
} foo;
won't link.
struct foo
{
...
void reset();
};
links fine.
So, maybe just a lack of understanding on my part about the way typedefs work in this context?
| I think that your problem (and I don't have a standards quote to back this up) is that because your struct doesn't have a name, your member function also does not have a globally identifiable name.
Although you're allowed to use a typedef name to introduce a member function definition, that member function must be part of a named type if you are going to be able to link it to a definition in a different TU.
typedef struct S_ { void reset(); } S;
void S::reset() // OK, but the function actually has id: S_::reset()
{
// ...
}
typedef struct { void reset(); } T;
void T::reset() // OK, defintion of anonymous struct's reset(),
// but this isn't an id that can cross TUs.
{
// ...
}
Edit: This could be a gcc bug, though.
7.1.3 [dcl.typedef] If the typedef declaration defines and unnamed class (...), the first typedef-name declared by the declaration to be that class type (...) is used to denote the class type (...) for linkage purposes only (3.5).
Edit:
Or gcc might be right. While the class has external linkage via its typedef name (3.5/4), a member function has external linkage only if the name of the class has external linkage. Although the class has external linkage and it has a name for linkage purposes only it is still an unnamed class, so it's member functions have no linkage.
|
2,516,896 | 2,517,305 | Presenting MVC to Old C++ Spaghetti Coders? | I wish to present the idea of MVC to a bunch of old C++ spaghetti coders (at my local computer club).
One of them that has alot of influence on the rest of the group seems to finally be getting the idea of encapsulation (largely due in part to this website).
I was hoping that I could also point him in the right direction by showing him Model View Controller, but I need to do it in a way that makes sense to him, as well as it probably needs to be written in C/C++!
I realize that MVC is a very old architectural pattern so it would seem to me that there should be something out there that would do the job.
I'm more of a web developer, so I was wondering if anybody out there who is a good C/C++ coder could tell me what it is that made the MVC light switch turn on in your head.
| Don't start off with MVC. Start off with Publish / Subscribe (AKA the "listener" pattern).
Without the listener pattern fully understood, the advantages of MVC will never be understood. Everyone can understand the need to update something else when something changes, but few think about how to do it in a maintainable manner.
Present one option after another, showing each option's weaknesses and strengths: making the variable a global, merging the other portion of code into the variable holder, modifying the holder to directly inform the others, and eventually creating a standard means of registering the intent to listen.
Then show how the full blown listener can really shine. Write a small "model" class and add half a dozen "listeners" and show how you never had to compromise the structure of the original class to add "remote" updates.
Once you get this down, move the idea into to the "model view" paradigm. Throw two or three different views on the same model, and have everyone amazed on how comparatively easy it is to add different views of the same information.
Finally discuss the need to manage views and update data. Note that the input is partially dependent on items which are not in the view or the model (like the keyboard and mouse). Introduce the idea of centralizing the processing where a "controller" needs to coordinate which models to create and maintain in memory, and which views to present to the user.
Once you do that, you'll have a pretty good introduction to MVC.
|
2,516,960 | 2,516,994 | C++ using this pointer in constructors | In C++, during a class constructor, I started a new thread with this pointer as a parameter which will be used in the thread extensively (say, calling member functions). Is that a bad thing to do? Why and what are the consequences?
My thread start process is at the end of the constructor.
| The consequence is that the thread can start and code will start executing a not yet fully initialized object. Which is bad enough in itself.
If you are considering that 'well, it will be the last sentence in the constructor, it will be just about as constructed as it gets...' think again: you might derive from that class, and the derived object will not be constructed.
The compiler may want to play with your code around and decide that it will reorder instructions and it might actually pass the this pointer before executing any other part of the code... multithreading is tricky
|
2,516,965 | 2,520,341 | How to setup directories in Visual Studio when using boost? | I have introduced boost to our code base, on my machine I created a boost directory called Thirdparty.Boost and added that as an additional include directory in my Visual Studio setting, all is fine.
However I now want to check in my changes, so the rest of the team can get them. Inorder to build the code they would need to setup boost as I have (problem number 1). In addition we have a build server, which will need changing (problem 2). I have a way of distributing boost to everyone including the build server, so that's not a problem
I need a way of referring to the boost directory without changing the default settings in Visual Studio. Why don't you change it on a project level I hear you cry? The solution has over 200 projects, which would require a lot of changes.
I just wondered if there was another way?
Cheers
Rich
| What about adding an environment variable on each of your developer's machines:
CL=-I<...the_boost_directory...>
i.e. on your machine:
CL=-IThirdparty.Boost
The MS compiler adds the value of the environment variable CL to its command line, so this should do the trick for you.
|
2,517,019 | 2,517,626 | Elegant way of parsing Data files for Simulation | I am working on this project where I need to read in a lot of data from .dat files and use the data to perform simulations. The data in my .dat file looks as follows:
DeviceID InteractingDeviceID InteractionStartTime InteractionEndTime
1 2 1101 1105
1,2 1101 and 1105 are tab delimited and it means Device 1 interacted with Device 2 at 1101 ms and ended the interaction at 1105ms.
I have a trace data sets that compile thousands of such interactions and my job is to analyze these interactions.
The first step is to parse the file. The language of choice is C++. The approach I was thinking of taking was to read the file, for every line that's read create a Device Object.
This Device object will contain the property DeviceId and an array/vector of structs, that will contain a list of all the devices the given DeviceId interacted with over the course of the simulation.The struct will contain the Interacting Device Id, Interaction Start Time and Interaction End Time.
I have a two fold question here:
Is my approach correct?
If I am on the right track, how do I rapidly parse these tab delimited data files and create Device objects without excessive memory overhead using C++?
A push in the right direction will be much appreciated.
Thanks
| Your approach seems to be correct given the information you've provided.
I'm assuming you'd be creating a class something like:
class device {
public:
int id;
vector<interaction> interactions;
void add_interaction(interaction add_me); // uses vector::insert
};
with
typedef struct interaction_t {
int other_device_id;
int start_time;
int end_time;
} interaction;
At that point, you should be able to read in the file, one line at a time, and pull out the data.
device* pDev = NULL;
interaction new_interaction;
ifstream ifs( "data.dat" );
char temp[MAX_LINE_LENGTH+1];
int id, other_id, start, end;
while(ifs.getline(temp, MAX_LINE_LENGTH)) {
sscanf(temp, "%i\t%i\t%i\t%i",
&id,
&new_interaction.other_device_id,
&new_interaction.start_time,
&new_interaction.end_time);
pDev = find_device_by_id(id);
pDev->add_interaction(new_interaction);
}
Code is untested and for illustration purposes only, but you can get the idea. The trick would be writing the find_device_by_id function (would return a pointer to the device object with a matching id field). This shouldn't require too heavy of a memory overhead per input line; if your input files are huge, you may not be able to store the data in memory and may have to store in a database instead.
|
2,517,050 | 2,517,110 | C++: Construction and initialization order guarantees | I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z and W. The main function instantiates an object of class X, which contains an object of class Y, and derives from class Z, so both constructors will be called. Additionally, the const char* parameter passed to X's constructor will be implicitly converted to an object of class W, so W's constructor must also be called.
What are the guarantees the C++ standard gives on the order of the calls to the copy constructors? Or, equivalently, what this program is allowed to print?
#include <iostream>
class Z {
public:
Z() { std::cout << "Z" << std::endl; }
};
class Y {
public:
Y() { std::cout << "Y" << std::endl; }
};
class W {
public:
W(const char*) { std::cout << "W" << std::endl; }
};
class X : public Z {
public:
X(const W&) { std::cout << "X" << std::endl; }
private:
Y y;
};
int main(int, char*[]) {
X x("x");
return 0;
}
edit: Is this correct?
W |
/ \ |
Z Y |
\ / |
X V
| In all classes construction order is guaranteed: base classes, as specified from left to right followed by member variables in the order declared in the class definition. A class's constructor body is executed once all of its bases' and members' constructions have completed.
In your example X is derived from Z and contains Y so the Z base object is constructed first, then the Y member y, then the construction of the X completes with the execution of X's constructor body.
The temporary W is needed to pass to the constructor of X, so it is constructed before the construction of the x begins and will be destroyed once the initialization of x completes.
So the program must print:
W
Z
Y
X
|
2,517,245 | 2,517,455 | Why, really, deleting an incomplete type is undefined behaviour? | Consider this classic example used to explain what not to do with forward declarations:
//in Handle.h file
class Body;
class Handle
{
public:
Handle();
~Handle() {delete impl_;}
//....
private:
Body *impl_;
};
//---------------------------------------
//in Handle.cpp file
#include "Handle.h"
class Body
{
//Non-trivial destructor here
public:
~Body () {//Do a lot of things...}
};
Handle::Handle () : impl_(new Body) {}
//---------------------------------------
//in Handle_user.cpp client code:
#include "Handle.h"
//... in some function...
{
Handle handleObj;
//Do smtg with handleObj...
//handleObj now reaches end-of-life, and BUM: Undefined behaviour
}
I understand from the standard that this case is headed towards UB since Body's destructor is non trivial.
What I'm trying to understand is really the root cause of this.
I mean, the problem seems to be "triggered" by the fact that Handle's dtor is inline, and so the compiler does something like the following "inline expansion" (almost pseudo-code here).
inline Handle::~Handle()
{
impl_->~Body();
operator delete (impl_);
}
In all translation units (only Handle_user.cpp in this case) where a Handle instance gets to be destroyed, right?
I just can't understand this: ok, when generating the above inline expansion the compiler doesn't have a full definition of the Body class, but why cannot it simply have the linker resolve for the impl_->~Body() thing and so have it call the Body's destructor function that's actually defined in its implementation file?
In other words: I understand that at the point of Handle destruction the compiler doesn't even know if a (non-trivial) destructor exists or not for Body, but why can't it do as it always does, that is leave a "placeholder" for the linker to fill in, and eventually have a linker "unresolved external" if that function is really not available?
Am I missing something big here (and in that case sorry for the stupid question)?
If that's not the case, I'm just curious to understand the rationale behind this.
| To combine several answers and add my own, without a class definition the calling code doesn't know:
whether the class has a declared destructor, or if the default destructor is to be used, and if so whether the default destructor is trivial,
whether the destructor is accessible to the calling code,
what base classes exist and have destructors,
whether the destructor is virtual. Virtual function calls in effect use a different calling convention from non-virtual ones. The compiler can't just "emit the code to call ~Body", and leave the linker to work out the details later,
(this just in, thanks GMan) whether delete is overloaded for the class.
You can't call any member function on an incomplete type for some or all of those reasons (plus another that doesn't apply to destructors - you wouldn't know the parameters or return type). A destructor is no different. So I'm not sure what you mean when you say "why can't it do as it always does?".
As you already know, the solution is to define the destructor of Handle in the TU which has the definition of Body, same place as you define every other member function of Handle which calls functions or uses data members of Body. Then at the point where delete impl_; is compiled, all the information is available to emit the code for that call.
Note that the standard actually says, 5.3.5/5:
if the object being deleted has
incomplete class type at the point of
deletion and the complete class has a
non-trivial destructor or a
deallocation function, the behavior is
undefined.
I presume this is so that you can delete an incomplete POD type, same as you could free it in C. g++ gives you a pretty stern warning if you try it, though.
|
2,517,362 | 2,517,387 | Why would you avoid C++ keywords in Java? | A popular editor uses highlighting to help programmers avoid using C++ keywords in Java. The following words are displayed using the same colors as a syntax error:
auto delete extern friend inline redeclared register signed sizeof
struct template typedef union unsigned operator
Why would this be considered important?
| To avoid confusion. The largest migration path in the entire industry over the last 15 years was from C++ to Java. Thus, it would be wise to avoid using those words in a new context where they no longer mean anything.
|
2,517,484 | 2,517,574 | How can I pass a C++ member function to a C API as a parameter | In my C++ program, I need to call this c API:
GConn* gnet_conn_new (const gchar *hostname,
gint port,
GConnFunc func);
where GConnFunc is defined as:
void (*GConnFunc) (GConn *conn);
My question is if I have a C++ class and have a member function like:
Class A {
public:
A();
void my_func (GConn* conn);
}
In my A::A() Constructor, how can I pass this->myfunc to gnet_conn_new as the GConnFunc parameter?
Thank you.
| Most APIs provide a pointer-sized 'user data' argument, which would look like this:
GConn* gnet_conn_new (const gchar *hostname,
gint port,
GConnFunc func,
void* user_data);
This would allow you to pass an instance in user_data and have your C function forward to the member function like this:
void my_func(GConn *conn, void* user_data)
{
((MyClass*)user_data)->MyMemberFunc(conn);
}
Perhaps your API has an alternative or similar 'user data' parameter somewhere. Otherwise, you can't really do it without globals or statics.
|
2,517,592 | 2,518,056 | Multithreading: apache portable runtime vs boost::thread? | Which way is better for a novice student who has never used boost?
When a new standard arrives, the answer will be obvious, but now I have doubts. Pro for boost is that it's much closer to future standard.
| Another pro for Boost is that it uses common C++ idioms for describing, initializing, running, and joining threads (using idioms like RAII and allowing the use of functors and similar C++-specific tools).
Lower-level libraries like APR rely on the use of C-like idioms, which for a C++ developer can prove to be more error-prone (such as the use of function pointers).
In my opinion, Boost::Thread is easier to use because it allows me to use the C++ idioms that I use elsewhere in my code. With APR, I may as well be using pthreads.
|
2,517,946 | 2,517,970 | How to swap out a memory block? | How to make a block of memory allocated by malloc() or new:
immediately swapped out,
or lazily initialized.
In fact, I'm trying to reserve an address space. How to accomplish this?
PS. How to verify, from the user space, if a memory block is swapped out?
| To reserve a chunk of address space:
On unix, sbrk() or mmap().
On Windows, VirtualAlloc().
|
2,518,254 | 2,518,729 | 32bit to 64bit inline assembly porting | I have a piece of C++ code (compiled with g++ under a GNU/Linux environment) that load a function pointer (how it does that doesn't matter), pushes some arguments onto the stack with some inline assembly and then calls that function, the code is like :
unsigned long stack[] = { 1, 23, 33, 43 };
/* save all the registers and the stack pointer */
unsigned long esp;
asm __volatile__ ( "pusha" );
asm __volatile__ ( "mov %%esp, %0" :"=m" (esp));
for( i = 0; i < sizeof(stack); i++ ){
unsigned long val = stack[i];
asm __volatile__ ( "push %0" :: "m"(val) );
}
unsigned long ret = function_pointer();
/* restore registers and stack pointer */
asm __volatile__ ( "mov %0, %%esp" :: "m" (esp) );
asm __volatile__ ( "popa" );
I'd like to add some sort of
#ifdef _LP64
// 64bit inline assembly
#else
// 32bit version as above example
#endif
But i don't know inline assembly for 64bit machines, anyone could help me?
Thanks
| While it shouldn't be much of a problem to call a function pointer with the appropriate arguments in inline assembly, I don't think recoding this naively in x64 will help you, because the calling conventions to be used are very probably different (defaults for 32bit and 64bit linux are definitely different). Have a look here for details. So I guess, if you can get away without inline assembly in this case (see the other answer), it'll be easier to port.
Edit: OK, I see you may have to use assembly. Here are some pointers.
According to Agner Fog's document, linux x64 uses RDI, RSI, RDX, RCX, R8, R9 and XMM0-XMM7 for parameter transfer. This implies that in order to achieve what you want (disregarding floating-point use) your function will have to:
(1) save all registers that need to be saved (RBX, RBP, R12-R15): Set aside space on the stack and move these registers there. This will be somthing along the lines of (Intel syntax):
sub rsp, 0xSomeNumber1
mov [rsp+i*8], r# ; insert appropriate i for each register r# to be moved
(2) Evaluate the number of arguments you will have to pass by stack to the target function. Use this to set aside the required space on the stack (sub rsp, 0xSomeNumber2), taking into account 0xSomeNumber1 so that the stack will be 16-byte aligned at the end, i.e. rsp must be a multiple of 16. Don't modify rsp after this until your called function has returned.
(3) Load your function arguments on the stack (if necessary) and in the registers used for parameter transfer. In my view, it's easiest if you start with the stack parameters and load register parameters last.
;loop over stack parameters - something like this
mov rax, qword ptr [AddrOfFirstStackParam + 8*NumberOfStackParam]
mov [rsp + OffsetToFirstStackParam + 8*NumberOfStackParam], rax
Depending on how you set up your routine, the offset to the first stack parameter etc. may be unnceccessary. Then set up the number of register-passed arguments (skipping those you don't need):
mov r9, Param6
mov r8, Param5
mov rcx, Param4
mov rdx, Param3
mov rsi, Param2
mov rdi, Param1
(4) Call the target function using a different register from the above:
call qword ptr [r#] ; assuming register r# contains the address of the target function
(5) Restore the saved registers and restore rsp to the value it had on entry to your function. If necessary, copy the called function's return value wherever you want to have them. That's all.
Note: the above sketch does not take account of floating point values to be passed in XMM registers, but the same principles apply.
Disclaimer: I have done something similar on Win64, but never on Linux, so there may be some details I am overlooking. Read well, write your code carefully and test well.
|
2,518,305 | 2,518,358 | What is the difference between set and hashset in C++ STL? | When should I choose one over the other?
Are there any pointers that you would recommend for using the right STL containers?
| hash_set is an extension that is not part of the C++ standard. Lookups should be O(1) rather than O(log n) for set, so it will be faster in most circumstances.
Another difference will be seen when you iterate through the containers. set will deliver the contents in sorted order, while hash_set will be essentially random (Thanks Lou Franco).
Edit: The C++11 update to the C++ standard introduced unordered_set which should be preferred instead of hash_set. The performance will be similar and is guaranteed by the standard. The "unordered" in the name stresses that iterating it will produce results in no particular order.
|
2,518,796 | 2,518,839 | Resolving namespace conflicts | I've got a namespace with a ton of symbols I use, but I want to overwrite one of them:
external_library.h
namespace LottaStuff
{
class LotsOfClasses {};
class OneMoreClass {};
};
my_file.h
using namespace LottaStuff;
namespace MyCustomizations
{
class OneMoreClass {};
};
using MyCustomizations::OneMoreClass;
my_file.cpp
int main()
{
OneMoreClass foo; // error: reference to 'OneMoreClass' is ambiguous
return 0;
}
How do I get resolve the 'ambiguous' error without resorting to replacing 'using namespace LottaStuff' with a thousand individual "using xxx;" statements?
Edit: Also, say I can't edit my_file.cpp, only my_file.h. So, replacing OneMoreClass with MyCustomizations::OneMoreClass everywhere as suggested below wouldn't be possible.
| The entire point of namespaces is defeated when you say "using namespace".
So take it out and use namespaces. If you want a using directive, put it within main:
int main()
{
using myCustomizations::OneMoreClass;
// OneMoreClass unambiguously refers
// to the myCustomizations variant
}
Understand what using directives do. What you have is essentially this:
namespace foo
{
struct baz{};
}
namespace bar
{
struct baz{};
}
using namespace foo; // take *everything* in foo and make it usable in this scope
using bar::baz; // take baz from bar and make it usable in this scope
int main()
{
baz x; // no baz in this scope, check global... oh crap!
}
One or the other will work, as well as placing one within the scope for main. If you find a namespace truly tedious to type, make an alias:
namespace ez = manthisisacrappilynamednamespace;
ez::...
But never use using namespace in a header, and probably never in global scope. It's fine in local scopes.
|
2,518,816 | 2,518,864 | What's the usage if I provide an implementation for a pure virtual function in C++ | I know that it's OK for a pure virtual function to have an implementation. However, why it is like this? Is there conflict for the two concepts? What's the usage? Can any one offer any example?
| Was addressed in GotW #31. Summary:
There are three main reasons you might
do this. #1 is commonplace, #2 is
pretty rare, and #3 is a workaround
used occasionally by advanced
programmers working with weaker
compilers.
Most programmers should only ever use #1.
... Which is for pure virtual destructors.
|
2,518,921 | 2,519,007 | Adding an inheritance to an Qt designed object | I have a problem and I want to implement the MVC pattern to my QT application, that's why I need for example to inherite in my QTableWidget about another class like
myClass
{
myMethod();
}
but our QTableWidget is contained by our Mainwidows that is designed by the QT designer and generate an ui_MainWindow class !
Do you know how to do that ?
Is that a method inside the Qt Designer to do that ? or another method ?
Thank you for your answer !
| You can use custom objects in QDesigner. Right click on the widget that you want to have as an instance of a something that is not available in designer and select "Promote to ...". In that dialog you can enter a custom class and a include file where the declaration for your class can be found.
BUT Qt implements uses MVC for a lot of the classes look at QTableView as opposed to QTableWidget, QTableView uses QAbstractItemModel as the model class and there is a pretty strict separation between the view and the model. See also An Introduction to Model/View Programming @ Nokia
|
2,518,969 | 2,519,101 | GCC, Unicode and __FUNCTION__ | I'm trying to make my project compile under GCC (Visual Studio compiles it flawlessly).
I have a custom assert function which throws a wstring message. A part of it is the _ _FUNCTION__ macro, which I "unicodize" using the WIDEN macro from MSDN
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
It compiles okay in MSVC, but it prints this in GCC:
error: ‘L__FUNCTION__’ was not declared in this scope
The only solution I could come with is to convert the contents of __FUNCTION __ to wstring on runtime using mbstowcs, but I would like to find a compile-time way to do it.
Thanks for help.
| In GCC __FUNCTION__ is a non-standard extension. To quote: GCC Online Docs
In GCC 3.3 and earlier, in C only,
__FUNCTION__ and __PRETTY_FUNCTION__ were treated as string literals; they
could be used to initialize char
arrays, and they could be concatenated
with other string literals. GCC 3.4
and later treat them as variables,
like __func__. In C++, __FUNCTION__
and __PRETTY_FUNCTION__ have always
been variables.
So adding L on the front of __FUNCTION__ is just going to turn it into L__FUNCTION__ which is probably undefined.
|
2,518,979 | 2,519,011 | How to transform a vector<int> into a string? | I am trying to pass a value from C++ to TCL. As I cannot pass pointers without the use of some complicated modules, I was thinking of converting a vector to a char array and then passing this as a null terminated string (which is relatively easy).
I have a vector as follows:
12, 32, 42, 84
which I want to convert into something like:
"12 32 42 48"
The approach I am thinking of is to use an iterator to iterate through the vector and then convert each integer into its string representation and then add it into a char array (which is dynamically created initially by passing the size of the vector). Is this the right way or is there a function that already does this?
| What about:
std::stringstream result;
std::copy(my_vector.begin(), my_vector.end(), std::ostream_iterator<int>(result, " "));
Then you can pass the pointer from result.str().c_str()
|
2,519,325 | 2,519,349 | C++ method parameter passed by reference - memory question | Assume,
void proc(CString& str)
{
str = "123";
}
void runningMethod()
{
CString str="ABC";
proc(str);
}
I understand that at the exit of runningMethod str will be deallocated automatically; in this case, how does C++ delete the old data ("ABC")?
Thanks,
Gil.
| "ABC" was overwritten when you said = "123".
Internally, a string is an array of characters. At start, it made a new buffer that contained {'A', 'B', 'C', '\0'}. When you assigned, it just wrote '1' over the 'A', and so on.
When it destructed, it deleted the buffer.
|
2,519,529 | 2,519,551 | Reading value at an address | I'm trying to make a program that reads the value at a certain address.
I have this:
int _tmain(int argc, _TCHAR* argv[])
{
int *address;
address = (int*)0x00000021;
cout << *address;
return 0;
}
But this gives a read violation error. What am I doing wrong?
Thanks
| You can only use a pointer that points to an actual object.
If you don't have an object at address 0x00000021, this won't work.
If you want to create an object on the free store (the heap), you need to do so using new:
int* address = new int;
*address = 42;
cout << *address;
delete address;
|
2,519,564 | 2,519,875 | how to write programs using advanced OpenType features? | How could I write a simple program using OpenType tables in order to dynamically render text?
please answer in :
assembly , C , C++ , C# , java or Python (and a little WPF:-)
or introduce libraries of them.
comments and answers about text rendering system of common Operating Systems, or designing text engines compatible with unicode 5.02 protocol are welcomed.
| I don't know if this will satisfy your needs or not, but I've used the FreeType library in the past to render TrueType text. It is quite flexible and easily ported between various platforms (Linux, Windows, OSX, etc.). Also, the licensing (BSD-style) is such that using it in commercial applications is not a problem.
|
2,519,603 | 2,519,623 | Debugging unmanaged code while debugging managed code | The .NET 3.5 application I am working on consists of bunch of different solutions. Some of these solutions consist of managed code(C#) and others have unmanaged code(C++). Methods written in C# communicate with the ones written in C++. I am trying to trace the dependencies between these various functions and I thought setting breakpoints on the solution consisting my C++ functions. One of the C# solutions have the startup project. I run this solution in debug mode with the expectation that the breakpoints in my unmanaged code will be hit but nothing really happens. Can somebody guide me through the process of debugging mixed applications such as these using the Visual Studio IDE?
Thanks
| By default a managed project will only start the debugger with managed debugging enabled. It doesn't consider that there are unmanaged projects in the same solution. In order to debug both you need to explicitly enable unmanaged code debugging.
Right Click on the project and select properties
Go to the Debug tab
Check "Enable Unmanaged code debugging"
|
2,519,627 | 2,519,651 | isalpha(<mychar>) == true evaluates to false? | string temp is equal to "ZERO:\t.WORD\t1" from my debugger. (the first line of my file)
string temp = RemoveWhiteSpace(data);
int i = 0;
if ( temp.length() > 0 && isalpha(temp[0]) )
cout << "without true worked" << endl;
if ( temp.length() > 0 && isalpha(temp[0]) == true )
cout << "with true worked" << endl;
This is my code to check if first character of temp is a a-z,A-Z. The first if statement will evaluate to true and the 2nd to false. WHY?!?!?! I have tried this even without the "temp.length() > 0 &&" and it still evaluates false. It just hates the "== true". The only thing I can think of is that isalpha() returns != 0 and true == 1. Then, you could get isalpha() == 2 != 1. But, I have no idea if C++ is that ... weird.
BTW, I dont need to know that the "== true" is logically pointless. I know.
output was
without true worked
Compiled with CodeBlock using GNU GCC on Ubuntu 9.10 (if this matters any)
| The is* functions are only guaranteed to return a non-zero value if true, NOT necessarily a 1. A typical implementation is table based, with one entry in the table for each character value, and a set of bits defining which bit means what. The is* function will just AND the right bitmask with the table value, and return that, which will only be the value 1 for whichever type happens to have been given bit position 0.
E.g.:
#define __digit 1
#define __lower 2
#define __upper 4
extern int __type_table[];
int isdigit(int c) {
return __type_table[c+1] & __digit;
}
int isalpha(int c) {
return __type_table[c+1] & (__lower | __upper);
}
int islower(int c) {
return __type_table[c+1] & __lower;
}
int isupper(int c) {
return __type_table[c+1] & __upper;
}
Where __type_table is defined as something like int __type_table[UINT_MAX+1]; and would be initialized so (for example) __type_table['0'+1] == __digit and __type_table['A'+1] == __upper.
In case you care, the '+1' part is to leave a spot at the beginning of the table for EOF (which is typically defined as -1).
|
2,519,645 | 2,519,735 | Trouble calculating correct decimal digits | I am trying to create a program that will do some simple calculations, but am having trouble with the program not doing the correct math, or placing the decimal correctly, or something. Some other people I asked cannot figure it out either.
Here is the code: http://pastie.org/887352
When you enter the following data:
Weekly Wage: 500
Raise: 3
Years Employed: 8
It outputs the following data:
Year Annual Salary
1 $26000.00
2 $26780.00
3 $27560.00
4 $28340.00
5 $29120.00
6 $29900.00
7 $30680.00
8 $31460.00
And it should be outputting:
Year Annual Salary
1 $26000.00
2 $26780.00
3 $27583.40
4 $28410.90
5 $29263.23
6 $30141.13
7 $31045.36
8 $31976.72
Here is the full description of the task:
8.17 ( Pay Raise Calculator Application) Develop an application that computes the amount of money an employee makes each year over a user- specified number of years. Assume the employee receives a pay raise once every year. The user specifies in the application the initial weekly salary, the amount of the raise (in percent per year) and the number of years for which the amounts earned will be calculated. The application should run as shown in Fig. 8.22. in your text. (fig 8.22 is the output i posted above as what my program should be posting)
Opening the template source code file. Open the PayRaise.cpp file in your text editor or IDE.
Defining variables and prompting the user for input. To store the raise percentage and years of employment that the user inputs, define int variables rate and years, in main after line 12. Also define double variable wage to store the user’s annual wage. Then, insert statements that prompt the user for the raise percentage, years of employment and starting weekly wage. Store the values typed at the keyboard in the rate, years and wage variables, respectively. To find the annual wage, multiply the new wage by 52 (the number of weeks per year) and store the result in wage.
Displaying a table header and formatting output. Use the left and setw stream manipulators to display a table header as shown in Fig. 8.22 in your text. The first column should be six characters wide. Then use the fixed and setprecision stream manipulators to format floating- point values with two positions to the left of the decimal point.
Writing a for statement header. Insert a for statement. Before the first semicolon in the for statement header, define and initialize the variable counter to 1. Before the second semicolon, enter a loop- continuation condition that will cause the for statement to loop until counter has reached the number of years entered. After the second semicolon, enter the increment of counter so that the for statement executes once for each number of years.
Calculating the pay raise. In the body of the for statement, display the value of counter in the first column and the value of wage in the second column. Then calculate the new weekly wage for the following year, and store the resulting value in the wage variable. To do this, add 1 to the percentage increase (be sure to divide the percentage by 100.0 ) and multiply the result by the current value in wage.
Save, compile and run the application. Input a raise percentage and a number of years for the wage increase. View the results to ensure that the correct years are displayed and that the future wage results are correct.
Close the Command Prompt window.
We can not figure it out! Any help would be greatly appreciated, thanks!
| I changed your for loop to this:
cout << (i+1) << " $" << wage*52 << "\n";
wage = wage * (1+(raise/100.0));
And it did worked!. I see you didn't understand the language of the problem.
|
2,519,727 | 2,520,385 | Linking Boost to my C++ project in Eclipse | I'm trying to get the Boost library working in my C++ projects in Eclipse. I can successfully build when using header-only libraries in Boost such as the example simple program in the "Getting Started" guide using the lambda header.
I cannot get my project to successfully link to the regex Boost library as shown later in the guide. Under my project properties -> c/c++ build -> settings -> tool settings tab -> libraries, I have added "libboost_regex" to the Libraries box, and "C:\Program Files\boost\boost_1_42_0\bin.v2\libs" to the Library search path box since this is where all the .lib files are. I've even tried adding "libboost_regex-mgw34-mt-d-1_42.lib" to the libraries box instead of "libboost_regex" since that is the exact file name, but this did not work either.
I keep getting an error that says "cannot find -llibboost_regex" when I try to build my project. Any ideas as to how I can fix this?
Edit: on Windows XP, using mingw, and I have tried "boost_regex" as well..
| I just went through the whole process of installing MinGW, compiling boost and installing Eclipse CDT and I'm able to compile simple programs using boost:regex. I'll write down all the steps. I hope that can be of help.
I've installed MinGW and MSYS in their default location.
Here are the step I took to build boost:
Download boost-jam-3.1.18-1-ntx86.zip from http://sourceforge.net/projects/boost/files/boost-jam
Put bjam.exe somewhere in your PATH
Unpack boost in C:\mingw\boost_1_42_0
Open an msys terminal window and cd /c/mingw/boost_1_42_0
In the boost directory run bjam --build-dir=build toolset=gcc stage
To configure Eclipse:
Add CDT to Eclipse 3.5 from the update site
Create a new C++ project
Under the Project menu select properties
Make sure the configuration is Debug [Active]
In "C/C++ General" > "Paths and Symbols"
Under the Includes tab select the GNU C++ language and add C:\MinGW\boost_1_42_0
Under the Library Paths tab add C:\MinGW\boost_1_42_0\stage\lib
In "C/C++ Build" > "Settings"
Select MinGW C++ Linker > Libraries
Click on the add button for Libraries (-l)
Type libboost_regex-mgw34-mt-d (without the .lib)
You can then go through the same steps for the Release configuration but use libboost_regex-mgw34-mt instead. Also make sure your source files include <boost/regex.hpp>
|
2,519,851 | 2,519,862 | How to deal with Warning C4100 in Visual Studio 2008 | For some reason my Visual Studio 2008 began to show warnings for code like:
"int main( int argc, char **argv)", which is really annoying.
The detailed warning ouputs are (you can ignore the line numbers):
1>.\main.cpp(86) : warning C4100: 'argv' : unreferenced formal parameter
1>.\main.cpp(86) : warning C4100: 'argc' : unreferenced formal parameter
I wonder if there are settings in Visual Studio 2008 that have been accidentally changed. Or how should I deal with this warning?
| If the parameters are unreferenced, you can leave them unnamed:
int main(int, char**)
{
}
instead of
int main(int argc, char** argv)
{
}
If you really want just to suppress the warning, you can do so using the /wd4100 command line option to the compiler or using #pragma warning(disable: 4100) in your code.
This is a level 4 warning; if you compile at a lower warning level, you won't get this warning. The warning level is set in the project properties (right-click project, select Properties; on the Configuration Properties -> C++ -> General, set "Warning Level").
|
2,520,130 | 2,520,156 | Why are structs not allowed in template definitions? | The following code yields an error error: ‘struct Foo’ is not a valid type for a template constant parameter:
template <struct Foo>
struct Bar {
};
Why is that so?
template <class Foo>
struct Bar {
};
works perfectly fine and even accepts an struct as argument.
| This is just an artifact of the syntax rules - the syntax just lets you use the class or typename keywords to indicate a type template parameter. Otherwise the parameter has to be a 'non-type' template parameter (basically an integral, pointer or reference type).
I suppose Stroustrup (and whoever else he might have taken input from) decided that there was no need to include struct as a a keyword to indicate a type template parameter since there was no need for backwards compatibility with C.
In fact, my recollection (I'll have to do some book readin' when I get back home) is that when typename was added to indicate a template type parameter, Stroustrup would have liked to take away using the class keyword for that purpose (since it was confusing), but there was too much code that relied on it.
Edit:
Turns out the story is more like (from a blog entry by Stan Lippman):
The reason for the two keywords is
historical. In the original template
specification, Stroustrup reused the
existing class keyword to specify a
type parameter rather than introduce a
new keyword that might of course break
existing programs. It wasn't that a
new keyword wasn't considered -- just
that it wasn't considered necessary
given its potential disruption. And up
until the ISO-C++ standard, this was
the only way to declare a type
parameter.
Reuses of existing keywords seems to
always sow confusion. What we found is
that beginners were [wondering]
whether the use of the class
constrained or limited the type
arguments a user could specify to be
class types rather than, say, a
built-in or pointer type. So, there
was some feeling that not having
introduced a new keyword was a
mistake.
During standardization, certain
constructs were discovered within a
template definition that resolved to
expressions although they were meant
to indicate declarations
...
The committee decided that a new
keyword was just the ticket to get the
compiler off its unfortunate obsession
with expressions. The new keyword was
the self-describing typename.
...
Since the keyword was on the payroll,
heck, why not fix the confusion caused
by the original decision to reuse the
class keyword. Of course, given the
extensive body of existing code and
books and articles and talks and
postings using the class keyword, they
chose to also retain support for that
use of the keyword as well. So that's
why you have both.
|
2,520,413 | 2,591,731 | setcontext and makecontext to call a generic function pointer | In another question I had the problem to port the code:
unsigned long stack[] = { 1, 23, 33, 43 };
/* save all the registers and the stack pointer */
unsigned long esp;
asm __volatile__ ( "pusha" );
asm __volatile__ ( "mov %%esp, %0" :"=m" (esp));
for( i = 0; i < sizeof(stack); i++ ){
unsigned long val = stack[i];
asm __volatile__ ( "push %0" :: "m"(val) );
}
unsigned long ret = function_pointer();
/* restore registers and stack pointer */
asm __volatile__ ( "mov %0, %%esp" :: "m" (esp) );
asm __volatile__ ( "popa" );
To a 64bit platform and many guys told me I should use the setcontext() and makecontext() functions set instead due to the calling conversion differences between 32 and 64 bits and portability issues.
Well, I really can't find any useful documentation online, or at least not the kind I need to implement this, so, how can I use those functions to push arguments onto the stack, call a generic function pointer, obtain the return value and then restore the registers?
| Finally i'm using libffi .
|
2,520,843 | 2,521,681 | operator new for array of class without default constructor | For a class without default constructor, operator new and placement new can be used to declare an array of such class.
When I read the code in More Effective C++, I found the code as below(I modified some part).....
My question is, why [] after the operator new is needed?
I test it without it, it still works. Can any body explain that?
class A {
public:
int i;
A(int i):i(i) {}
};
int main()
{
void *rawMemory = operator new[] (10 * sizeof(A)); // Why [] needed here?
A *p = static_cast<A*>(rawMemory);
for(int i = 0 ; i < 10 ; i++ ) {
new(&p[i])A(i);
}
for(int i = 0 ; i < 10 ; i++ ) {
cout<<p[i].i<<endl;
}
for(int i = 0 ; i < 10 ; i++ ) {
p[i].~A();
}
return 0;
}
| I'm surprised that Effective C++ would be advising you to use something as hackish as a void*.
new[] does a very specific thing: it allocates a dynamically sized array. An array allocated with it should be passed to delete[]. delete[] then reads a hidden number to find how many elements are in the array, and destroys the objects as you have done with p[i].~A();.
However, this usage is incompatible with that. The array is statically sized, and there's no way to get that hidden number or dynamic-size destruction without properly using new[] (no operator), in turn requiring a default constructor. A genuine weakness of C++.
If you called delete[] at the end of main as others have suggested, your code could crash. Instead you need to use operator delete[], which looks like a typo and is just an accident waiting to happen.
Use non-array operator new and operator delete and ample comments if you must use this trick. But I wouldn't consider this particularly effective C++.
|
2,520,900 | 2,521,703 | Portable end of line | is there any way to automatically use correct EOL character depending on the OS used?
I was thinking of something like std::eol?
I know that it is very easy to use preprocessor directives but curious if that is already available.
What I am interested in is that I usually have some messages in my applications that I combine later into a single string and I want to have them separated with a EOL. I know that I could use std::stringstream << endl but it seems to be an overkill sometimes instead of a regular append.
| std::endl is defined to do nothing besides write '\n' to the stream and flush it (§27.6.2.7). Flushing is defined to do nothing for a stringstream, so you're left with a pretty way of saying mystringstream << '\n'. The standard library implementation on your OS converts \n appropriately, so that's not your concern.
Thus endl is already the ultimate in performance and portability, and the only other thing you could want is << '\n' if you are trying to efficiently write to a file (not a stringstream). Well, << '\n' does also eliminate the pointless virtual call to stringbuf::flush. Unless profiling shows that empty function call to be taking time, don't think about it.
|
2,521,130 | 2,521,141 | Copy hashtable to another hashtable using c++ | I am starting with c++ and need to know, what should be the approach to copy one hashtable to another hashtable in C++?
We can easily do this in java using: HashMap copyOfOriginal=new HashMap(original);
But what about C++? How should I go about it?
UPDATE
Well, I am doing it at a very basic level,perhaps the java example was a wrong one to give. This is what I am trying to implement using C++:
I have this hash array and each element of the array is the head of a linked list. Which has it's individual nodes (data and next pointer).
And now, I need to copy the complete hash array and the linked list each node is pointing to.
| Well, what hash table implementation are you using? There is no hash table provided by the current version of ISO C++. That said, if your hash table class does not make operator= and its copy constructor private, then it would be a reasonable assumption that both will behave as expected. If not, I'd consider it a bug.
As an aside std::unordered_map is being added in ISO C++ 2010, but ISO C++ 1998 and ISO C++ 1998 with the 2003 amendments do not have a hash map container. Microsoft provided a non-standard "std::hash_map", which they should never have placed in the "std::" namespace. They have since moved it to "stdext::" (which is good news). Some other vendors copied MSFT to make their compilers compatible.
If you are anxious to use a hash table implementation right away, then use boost::unordered_map from the Boost C++ Libraries. The Boost C++ Libraries are open source, very popular, and high quality.
EDIT
Based on your updated question, you will need to create your own copy constructor, a swap function, and an implementation of operator= in order to do this. Usually operator= is trivial once you have swap and a copy constructor in place. Here is a sketch of how you would do this:
template<typename T>
HashTable<T>::HashTable(const HashTable<T>& o)
{
// pseudo code:
// initialize as in HashTable<T>::HashTable()
// for each key/value pair in o:
// insert that key/value pair into this instance
//
// NOTE:
// if your hash table is sized so that the number of
// elements is a prime number, you can do better
// than the pseudo-code given above, but otherwise
// copying element by element is the way to go.
//
// BEGIN YOUR CODE
// ...
// END YOUR CODE
}
template<typename T> HashTable<T>&
HashTable<T>::swap(HashTable<T>& o)
{
// Swap data pointers
T* datatmp = _data;
_data = o._data;
o._data = datatmp;
// Swap capacity
size_t captmp = _capacity;
_capacity = o._capacity;
o._capacity = captmp;
// Swap other info
// ...
// Report self
return *this;
}
template<typename T> HashTable<T>&
HashTable<T>::operator=(const HashTable<T>& o)
{
HashTable<T> cpy(o);
return swap(cpy);
}
You will have to take the signatures from the above and add them to your declaration. I should also point out that one reason that operator= tends to be implemented in terms of swap is that, not only is it very simple to do and having a swap function makes your code very fast when that operation is needed, but also for the purposes of exception safety... your swap should pretty much never fail, but copy construction might... so if the copy construction throws an exception, you haven't thrown the object's state to hell.
|
2,521,200 | 2,521,215 | overriding enumeration base type using pragma or code change | Problem:
I am using a big C/C++ code base which works on gcc & visual studio compilers where enum base type is by default 32-bit(integer type).
This code also has lots of inline + embedded assembly which treats enum as integer type and enum data is used as 32-bit flags in many cases.
When compiled this code with realview ARM RVCT 2.2 compiler, we started getting many issues since realview compiler decides enum base type automatically based on the value an enum is set to. http://www.keil.com/support/man/docs/armccref/armccref_Babjddhe.htm
For example,
Consider the below enum,
enum Scale {
TimesOne, //0
TimesTwo, //1
TimesFour, //2
TimesEight, //3
};
This enum is used as a 32-bit flag. but compiler optimizes it to unsigned char type for this enum.
Using --enum_is_int compiler option is not a good solution for our case, since it converts all the enum's to 32-bit which will break interaction with any external code compiled without --enum_is_int.
This is warning i found in RVCT compilers & Library guide,
The --enum_is_int option is not
recommended for general use and is not
required for ISO-compatible source.
Code compiled with this option is not
compliant with the ABI for the ARM
Architecture (base standard) [BSABI],
and incorrect use might result in a
failure at runtime. This option is not
supported by the C++ libraries.
Question
How to convert all enum's base type (by hand-coded changes) to use 32-bit without affecting value ordering?
enum Scale {
TimesOne=0x00000000,
TimesTwo, // 0x00000001
TimesFour, // 0x00000002
TimesEight, //0x00000003
};
I tried the above change. But compiler optimizes this also for our bad luck. :(
There is some syntax in .NET like
enum Scale: int
Is this a ISO C++ standard and ARM compiler lacks it?
There is no #pragma to control this enum in ARM RVCT 2.2 compiler. Is there any hidden pragma available ?
| I know that a lot of the windows headers use the following:
enum SOME_ENUM {
ONE = 1,
TWO = 2,
//...
FORCE_DWORD = 0x7FFFFFFF
};
|
2,521,401 | 2,521,431 | C++ Pointer member function with templates assignment with a member function of another class | class IShaderParam{
public:
std::string name_value;
};
template<class TParam>
class TShaderParam:public IShaderParam{
public:
void (TShaderParam::*send_to_shader)( const TParam&,const std::string&);
TShaderParam():send_to_shader(NULL){}
TParam value;
void up_to_shader();
};
typedef TShaderParam<float> FloatShaderParam;
typedef TShaderParam<D3DXVECTOR3> Vec3ShaderParam;
In another class, I have a vector of IShaderParams* and functions that i want to send to "send_to_shader". I'm trying assign the reference of these functions like this:
Vec3ShaderParam *_param = new Vec3ShaderParam;
_param->send_to_shader = &TShader::setVector3;
This is the function:
void TShader::setVector3(const D3DXVECTOR3 &vec, const std::string &name){
//...
}
And this is the class with IshaderParams*:
class TShader{
std::vector<IShaderParam*> params;
public:
Shader effect;
std::string technique_name;
TShader(std::string& afilename):effect(NULL){};
~TShader();
void setVector3(const D3DXVECTOR3 &vec, const std::string &name);
When I compile the project with Visual Studio C++ Express 2008 I recieve this error:
Error 2 error C2440: '=' :can't make
the conversion 'void (__thiscall
TShader::* )(const D3DXVECTOR3 &,const
std::string &)' a 'void (__thiscall
TShaderParam::* )(const TParam
&,const std::string &)'
c:\users\isagoras\documents\mcv\afoc\shader.cpp
127
Can I do the assignment? No? I don't know how :-S
Yes, I know that I can achieve the same objective with other techniques, but I want to know how can I do this..
| Presumably TShader::send_to_shader is a c-style function pointer?
Member functions cannot be used as function pointer callbacks - they require a this parameter.
Static member functions and global functions can be used as function pointers.
So you can either
pass the this manually as a parameter to a static function callback, which in turn invokes the member function on the appropriate instance
use an interface instead of a function
use a functor
All three require slight architectural changes.
|
2,521,629 | 2,521,702 | Did anyone give these smart pointers (auto_any, scoped_any, shared_any) a test drive? | I'm investigating smart pointers with "shared" functionality for Windows CE and Mobile, where the VS 2008 tr1 std::shared_ptr cannot be used (due to linkage to a v.9 dll not present on CE, obviously, if I understand it correctly).
There's a semi-old MSDN Magazine article with sources from a Microsoftie (Eric Niebler): Achieve More Reliable Resource Management with Our Custom C++ Classes.
The reasoning, design and implementation of his shared_any looks solid, but I'm wondering if anyone ever actually tested the lot on any platform (not necessarily WinCe/WM)?
| You might want to use boost::shared_ptr. As I understand it, the Boost.SmartPointer library is a header-only library, and so you can just copy over the headers you need from Boost to get everything working.
|
2,521,633 | 2,521,674 | Casting warnings in methods with variable arguments | Sorry if the question isn't correct, I'm very new in Objective-C.
I understand why this code throw the Warning: "warning: passing argument 1 of 'initWithObjectsAndKeys:' makes pointer from integer without"
NSDictionary *dictNames =
[[NSDictionary alloc] initWithObjectsAndKeys:
3, @"",
4, @"",
5, @"",nil];
Keys and Values of a NSDictionary must be NSObject and not fundamental types, like the integers 3, 4 and 5. (Correct me if necessary).
But I don't understand why this warning dissapears with the only "correct typing" of the first Key.
NSDictionary *dictNames =
[[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInteger:3], @"",
4, @"",
5, @"",nil];
It's because NSDictionary assumes the type of the other Keys? Is correct this manner of initialization?
| The prototype of the method you mentioned is
-(id)initWithObjectsAndKeys:(id)firstObject, ...;
Thus the first parameter must be an ObjC object. But the rest are passed by varargs. In C, any primitives can be passed as vararg arguments (think printf). Hence the compiler won't issue any warnings.
While the compiler is incapable of chekcing the types of the vararg arguments, it doesn't mean passing non-id into the method is valid.
|
2,521,699 | 2,521,710 | Need help in resolving a compiler error: error: invalid conversion from ‘int’ to ‘GIOCondition’ | I have a simple cpp file which uses GIO. I have stripped out everything to show my compile error:
Here is the error I get:
My.cpp:16: error: invalid conversion from ‘int’ to ‘GIOCondition’
make[2]: *** [My.o] Error 1
Here is the complete file:
#include <glib.h>
static gboolean
read_socket (GIOChannel *gio, GIOCondition condition, gpointer data)
{
return false;
}
void createGIOChannel() {
GIOChannel* gioChannel = g_io_channel_unix_new(0);
// the following is the line causing the error:
g_io_add_watch(gioChannel, G_IO_IN|G_IO_HUP, read_socket, NULL);
}
I have seen other example using gio, and I am doing the same thing in term of calling G_IO_IN|G_IO_HUP.
And the documentation http://www.gtk.org/api/2.6/glib/glib-IO-Channels.html, said I only need to include , which I did.
Can you please tell me how to resolve my error?
One thing I can think of is I am doing this in a cpp file. But g_io_add_watch is a c function?
Thank you for any help. I have spent hours on this but did not get anywhere.
| You can Cast it
(GIOCondition) G_IO_IN|G_IO_HUP
or
void createGIOChannel() {
GIOChannel* gioChannel = g_io_channel_unix_new(0);
// the following is the line causing the error:
GIOCondition cond = G_IO_IN|G_IO_HUP;
g_io_add_watch(gioChannel, cond , read_socket, NULL);
}
|
2,521,869 | 2,521,902 | Constant expression with custom object | I'm trying to use an instant of a custom class as a template parameter.
class X {
public:
X() {};
};
template <class Foo, Foo foo>
struct Bar {
};
const X x;
Bar<X, x> foo;
The compiler states that x cannot appear in a constant expression. Why that? There is everything given to construct that object at compile time.
| You can't do it. Standard 14.1 says:
4 A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
— integral or enumeration type,
— pointer to object or pointer to function,
— reference to object or reference to function,
— pointer to member.
5 [ Note: other types are disallowed either explicitly below or implicitly by the rules governing the form of template-arguments
(14.3). —end note ] The top-level cv-qualifiers on the template-parameter are ignored when determining its
type.
|
2,522,159 | 2,526,656 | boost smart pointers and BOOST_NO_MEMBER_TEMPLATES | After some struggling I managed to get boost smart pointers to build for Windows CE/Mobile at warning level 4.
I found the least-resistance-way to get rid of compile errors and warnings to be
#define BOOST_NO_MEMBER_TEMPLATES
What does it actually mean? Did I sell my soul to the devil? Will all hell break loose when I actually use the types?
| There shouldn't be any bad effects per se, just a loss of functionality.
A member template is a member function that is a template, for example:
struct foo
{
template <typename T>
void i_am_not_supported_sometimes(void);
};
So you don't get undefined behavior or anything, you just can't program things in a most generic manner. I think a definitive "is this bad" answer depends on exactly what it was being used for and what the work-around was.
Looking at smart_ptr, for example, the no-member-templates version literally just takes out the member templates, such as:
template<class Y>
explicit shared_ptr( Y * p ): px( p ), pn( p ) // Y must be complete
{
boost::detail::sp_enable_shared_from_this( this, p, p );
}
And replaces Y with T, so you lose the ability for some automatic conversions.
|
2,522,299 | 2,522,311 | C++ catch blocks - catch exception by value or reference? |
Possible Duplicate:
catch exception by pointer in C++
I always catch exceptions by value. e.g
try{
...
}
catch(CustomException e){
...
}
But I came across some code that instead had catch(CustomException &e) instead. Is this a)fine b)wrong c)a grey area?
| The standard practice for exceptions in C++ is ...
Throw by value, catch by reference
Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException which inherits from CustomException and overrides items like an error code. If a MyException type was thrown your catch block would cause it to be converted to a CustomException instance which would cause the error code to change.
|
2,522,687 | 2,522,710 | Why isn't the reference counter in boost::shared_ptr volatile? | In the boost::shared_ptr destructor, this is done:
if(--*pn == 0)
{
boost::checked_delete(px);
delete pn;
}
where pn is a pointer to the reference counter, which is typedefed as
shared_ptr::count_type -> detail::atomic_count -> long
I would have expected the long to be volatile long, given threaded usage and the non-atomic 0-check-and-deletion in the shared_ptr destructor above. Why isn't it volatile?
EDIT:
It turns out I looked at the header used when multi-threaded usage is not specified (atomic_count.hpp). In atomic_count_win32.hpp, the decrement is properly implemented for multithreaded usage.
| Because volatile is not necessary for multithreading, and does nothing beneficial, but potentially destroys a number of optimizations.
In order to ensure safe multithreaded access to a variable, the primitive we need is a memory barrier, which provides both the guarantee of volatile and a few others (it prevents memory access reordering across the barrier, which volatile doesn't do)
I believe shared_ptr uses atomic operations when possible, which implicitly provide a memory barrier. Otherwise it falls back to a mutex, which also provides a memory barrier.
See Why is volatile not considered useful in multithreaded C or C++ programming? or http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/ for more details
Edit
count_type is not a long in the general case. It is convertible to a long. If you look in atomic_count.hpp, the typedef to long is only applied if no threading is available (in which case of course, no synchronization is necessary). Otherwise it uses the implementation defined in boost/smart_ptr/detail/atomic_count_pthreads.hpp or boost/smart_ptr/detail/atomic_count_win32.hpp or one of the other files listed. And those are synchronized wrapper classes that ensures all operations are done atomically.
|
2,522,688 | 2,577,897 | Hook filtering Keyboards HKEYS issue in c | I am filtering the HKEYS by using Hook filtering function, I use the following code to disable Alt+Tab, Alt+Esc, Ctrl+Esc, Windows Key
if (((lParam.vkCode == 9) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 32))||
((lParam.vkCode == 27) && (lParam.flags == 0)) ||
((lParam.vkCode == 91) && (lParam.flags == 1)) ||
((lParam.vkCode == 92) && (lParam.flags == 1)) ||
((true) && (lParam.flags == 32)))
return 1;
Can any one tell me how can I disable Ctrl+Alt+Del? I have tried a lot to filter this but unsuccessful for me.
| I have got answer of my own question, ctrl+alt+del can't filter out from hook, the only way to disable ctrl+alt+del is to modify the registry form your code..
|
2,522,915 | 2,524,312 | QTableWidget alignement with the borders of its parent QWidget | Let's consider we have QWidget that contains QTableWidget (only). So we want to resize the table by resizing the widget, and we dont want to have an indet between the QWidget border and cells of the table. What kind of property is making posible for QTableWidget to be aligned with the borders of it parent widget?
Thanks.
| First, you want to make sure the QTableWidget is placed inside a layout. For instance,
QTableWidget* tw = new QTableWidget(parent_widget);
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(tw);
parent_widget->setLayout(layout);
assuming parent_widget is already pointing to the widget containing the QTableWidget. This will ensure that the table resizes when the parent widget does. To have the table fill the entire space of the widget, just set the margin to zero on the layout. Try one of these:
layout->setMargin(0);
or
layout->setContentsMargins(0,0,0,0);
|
2,522,934 | 7,292,557 | Enabling Direct3D-specific features (transparency AA) | I am trying to enable transparency antialiasing in my Ogre-Direct3D application, but it just won't work.
HRESULT hres = d3dSystem->getDevice()->SetRenderState(D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('S', 'S', 'A', 'A'));
/// returned value : hres == S_OK !
This method is taken from NVidia's technical report.
I can enable transparency AA manually through the NVIDIA Control Panel, but surely I can't ask my users to do it like this. Anyone has any idea?
Thank you for your time,
Bill
| Next time you have this kind of a problem, be sure to debug what states are currently active et al.
For example you could enable direct3D debug mode and enable state changes logging.
As shown here: http://blog.rthand.com/post/2010/10/25/Capture-DirectX-1011-debug-output-to-Visual-Studio.aspx
Hope that helps,
Cheers,
Roel
|
2,523,025 | 2,523,042 | Unsigned double in C++? | Why doesn't C++ support unsigned double syntax?
| Because typical floating point formats don't support unsigned numbers. See, for instance, this list of IEEE 754 formats.
Adding a numerical format that isn't supported by common hardware just makes life difficult for compiler writers, and is probably not considered worth the effort.
|
2,523,099 | 2,525,450 | Where is cmcfg32.lib? | I found a source code on MSDN about how to enable/disable privileges in C++
According to the source code, the linker must include cmcfg32.lib, but it can't be found...
I tried to compile without including that lib, it compiles without any error, but when I launch my program, it crashes with a fatal error.
So please, if you know which SDK contains cmcfg32.lib, let me know ;)
Thanks!
| It looks (to me) like a minor error in the code. Delete the line:
#pragma comment(lib, "cmcfg32.lib")
Of, if you want the correct library linked automatically, change it to:
#pragma comment(lib, "advapi32.lib")
|
2,523,139 | 2,523,166 | Const references when dereferencing iterator on set, starting from Visual Studio 2010 | Starting from Visual Studio 2010, iterating over a set seems to return an iterator that dereferences the data as 'const data' instead of non-const.
The following code is an example of something that does compile on Visual Studio 2005, but not on 2010 (this is an artificial example, but clearly illustrates the problem we found on our own code).
In this example, I have a class that stores a position together with a temperature. I define comparison operators (not all them, just enough to illustrate the problem) that only use the position, not the temperature. The point is that for me two instances are identical if the position is identical; I don't care about the temperature.
#include <set>
class DataPoint
{
public:
DataPoint (int x, int y) : m_x(x), m_y(y), m_temperature(0) {}
void setTemperature(double t) {m_temperature = t;}
bool operator<(const DataPoint& rhs) const
{
if (m_x==rhs.m_x) return m_y<rhs.m_y;
else return m_x<rhs.m_x;
}
bool operator==(const DataPoint& rhs) const
{
if (m_x!=rhs.m_x) return false;
if (m_y!=rhs.m_y) return false;
return true;
}
private:
int m_x;
int m_y;
double m_temperature;
};
typedef std::set<DataPoint> DataPointCollection;
void main(void)
{
DataPointCollection points;
points.insert (DataPoint(1,1));
points.insert (DataPoint(1,1));
points.insert (DataPoint(1,2));
points.insert (DataPoint(1,3));
points.insert (DataPoint(1,1));
for (DataPointCollection::iterator it=points.begin();it!=points.end();++it)
{
DataPoint &point = *it;
point.setTemperature(10);
}
}
In the main routine I have a set to which I add some points. To check the correctness of the comparison operator, I add data points with the same position multiple times. When writing the contents of the set, I can clearly see there are only 3 points in the set.
The for-loop loops over the set, and sets the temperature. Logically this is allowed, since the temperature is not used in the comparison operators.
This code compiles correctly in Visual Studio 2005, but gives compilation errors in Visual Studio 2010 on the following line (in the for-loop):
DataPoint &point = *it;
The error given is that it can't assign a "const DataPoint" to a [non-const] "DataPoint &".
It seems that you have no decent (= non-dirty) way of writing this code in VS2010 if you have a comparison operator that only compares parts of the data members.
Possible solutions are:
Adding a const-cast to the line where it gives an error
Making temperature mutable and making setTemperature a const method
But to me both solutions seem rather 'dirty'.
It looks like the C++ standards committee overlooked this situation. Or not?
What are clean solutions to solve this problem?
Did some of you encounter this same problem and how did you solve it?
Patrick
| The iterator should give you a const reference (and that's what the Standard says it should do), because changing the thing referred to would destroy the validity of the set's underlying data structure - the set doesn't "know" that the field you are changing is not actually part of the key. The alternatives are to make changes by removing and re-adding, or to use a std::map instead.
|
2,523,165 | 2,523,204 | Can't access a map member from a pointer | That's my first question :)
I'm storing the configuration of my program in a Group->Key->Value form, like the old INIs. I'm storing the information in a pair of structures.
First one, I'm using a std::map with string+ptr for the groups info (the group name in the string key). The second std::map value is a pointer to the sencond structure, a std::list of std::maps, with the finish Key->Value pairs.
The Key->Value pairs structure is created dynamically, so the config structure is:
std::map< std::string , std::list< std::map<std::string,std::string> >* > lv1;
Well, I'm trying to implement two methods to check the existence of data in the internal config. The first one, check the existence of a group in the structure:
bool isConfigLv1(std::string);
bool ConfigManager::isConfigLv1(std::string s) {
return !(lv1.find(s)==lv1.end());
}
The second method, is making me crazy... It check the existence for a key inside a group.
bool isConfigLv2(std::string,std::string);
bool ConfigManager::isConfigLv2(std::string s,std::string d) {
if(!isConfigLv1(s))
return false;
std::map< std::string , std::list< std::map<std::string,std::string> >* >::iterator it;
std::list< std::map<std::string,std::string> >* keyValue;
std::list< std::map<std::string,std::string> >::iterator keyValueIt;
it = lv1.find(s);
keyValue = (*it).second;
for ( keyValueIt = keyValue->begin() ; keyValueIt != keyValue->end() ; keyValueIt++ )
if(!((*keyValueIt).second.find(d)==(*keyValueIt).second.end()))
return true;
return false;
}
I don't understand what is wrong. The compiler says:
ConfigManager.cpp||In member function ‘bool ConfigManager::isConfigLv2(std::string, std::string)’:|
ConfigManager.cpp|(line over return true)|error: ‘class std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >’ has no member named ‘second’|
But it has to have the second member, because it's a map iterator...
Any suggestion about what's happening?
Sorry for my English :P, and consider I'm doing it as a exercise, I know there are a lot of cool configuration managers.
| keyValueIt is not a map iterator, it is a list iterator.
You can just do
if (keyValueIt->find(d) != keyValueIt->end())
|
2,523,191 | 2,523,244 | A function's static and dynamic parent | I'm reading Thinking in C++ (vol. 2):
Whenever a function is called,
information about that function is
pushed onto the runtime stack in an
activation record instance (ARI), also
called a stack frame. A typical stack
frame contains (1) the address of the
calling function (so execution can
return to it), (2) a pointer to the ARI of
the function’s static parent (the
scope that lexically contains the
called function, so variables global
to the function can be accessed), and
(3) a pointer to the function that called
it (its dynamic parent). The path that
logically results from repetitively
following the dynamic parent links is
the dynamic chain, or call chain
I'm unable to comprehend what the author means as function's static and dynamic parent. Also am not able to differentiate between item 1, 2 or 3. They all seem to be the same. Can someone please explain this passage to me?
| This all sounds very odd to me. Static frame pointers are normally used in languages with lexical scope, such as functional languages, and the pascal family with their nested functions. Globals are bound once either at compile time or runtime, and shouldn't need frame pointers. (1) is valid, but (2) doesn't exist in C++, AFAIK.
I suspect that (3) was meant to refer to the parent frame pointer. Call stacks are usually setup as linked lists so that debuggers and related tools can walk them without requiring deep knowledge of the program.
|
2,523,516 | 2,523,538 | Why can I call a non-const member function pointer from a const method? | A co-worker asked about some code like this that originally had templates in it.
I have removed the templates, but the core question remains: why does this compile OK?
#include <iostream>
class X
{
public:
void foo() { std::cout << "Here\n"; }
};
typedef void (X::*XFUNC)() ;
class CX
{
public:
explicit CX(X& t, XFUNC xF) : object(t), F(xF) {}
void execute() const { (object.*F)(); }
private:
X& object;
XFUNC F;
};
int main(int argc, char* argv[])
{
X x;
const CX cx(x,&X::foo);
cx.execute();
return 0;
}
Given that CX is a const object, and its member function execute is const, therefore inside CX::execute the this pointer is const.
But I am able to call a non-const member function through a member function pointer.
Are member function pointers a documented hole in the const-ness of the world?
What (presumably obvious to others) issue have we missed?
| In this context object is a reference to a X, not a reference to a const X. The const qualifier would be applied to the member (i.e. the reference, but references can't be const), not to the referenced object.
If you change your class definition to not using a reference:
// ...
private:
X object;
// ...
you get the error you are expecting.
|
2,523,765 | 2,523,786 | QString to char* conversion | I was trying to convert a QString to char* type by the following methods, but they don't seem to work.
//QLineEdit *line=new QLineEdit();{just to describe what is line here}
QString temp=line->text();
char *str=(char *)malloc(10);
QByteArray ba=temp.toLatin1();
strcpy(str,ba.data());
Can you elaborate the possible flaw with this method, or give an alternative method?
| Well, the Qt FAQ says:
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QString str1 = "Test";
QByteArray ba = str1.toLocal8Bit();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
return app.exec();
}
So perhaps you're having other problems. How exactly doesn't this work?
|
2,523,802 | 2,523,831 | Should a method that waits for a change of state be const? | In a multithreaded scenario, I have a method like this:
bool WaitForChange( time_duration WaitTime ) const;
This method waits either until the state of the object has changed and returns true, or until the timeout times out (how do you say that?) and returns false.
My intuition is, that const is to protect against unwanted side-effects of the method itself, so this is fine. But then again, some user might think that the state of the could not have changed, since the method is declared const. Is that user stupid, or should I make the method non-const in order to avoid confusion?
| By declaring the method as const, you say "Calling this method doesn't change the state of the object." This is (hopefully) true. So make it const.
If anybody thinks, const-ness means "While this method is called, no one else can change the object state" than that person is wrong.
|
2,523,981 | 2,524,024 | Converting a pointer for a base class into an inherited class | I'm working on a small roguelike game, and for any object/"thing" that is not a part of the map is based off an XEntity class. There are several classes that depend on it, such as XPlayer, XItem, and XMonster.
My problem is, that I want to convert a pointer from XEntity to XItem when I know that an object is in item. The sample code I am using to pick up an item is this, it is when a different entity picks up an item it is standing over.
void XEntity::PickupItem()
{
XEntity *Ent = MapList; // Start of a linked list
while(true)
{
if(Ent == NULL) { break; }
if(Ent->Flags & ENT_ITEM)
{
Ent->RemoveEntity(); // Unlink from the map's linked list
XItem *Item = Ent // Problem is here, type-safety
// Code to link into inventory is here
break;
}
Ent = Ent->MapList;
}
}
My first thought was to create a method in XEntity that returns itself as an XItem pointer, but it creates circular dependencies that are unresolvable.
I'm pretty stumped about this one. Any help is greatly appreciated.
| If you know that the XEntity is actuall and XItem then you can use a static cast.
XItem* Item = static_cast<XItem *>(Ent);
However, you should review you design and see if you can operate on the entity in a way that means that you don't need to know what derived type it is. If you can give the base class a sufficiently rich interface you may be able eliminate the flag check type inspection.
|
2,524,233 | 2,524,322 | Speed accessing a std::vector by iterator vs by operator[]/index? | Say, I have a
std::vector<SomeClass *> v;
in my code and I need to access its elements very often in the program, looping them forward and backward .
Which is the fastest access type between those two ?
Iterator access:
std::vector<SomeClass *> v;
std::vector<SomeClass *>::iterator i;
std::vector<SomeClass *>::reverse_iterator j;
// i loops forward, j loops backward
for( i = v.begin(), j = v.rbegin(); i != v.end() && j != v.rend(); i++, j++ ){
// some operations on v items
}
Subscript access (by index)
std::vector<SomeClass *> v;
unsigned int i, j, size = v.size();
// i loops forward, j loops backward
for( i = 0, j = size - 1; i < size && j >= 0; i++, j-- ){
// some operations on v items
}
And, does const_iterator offer a faster way to access vector elements in case I do not have to modify them?
| The performance difference is likely negligable or none (the compiler might optimise them to be identical); you should worry about other things, like whether your program is correct (a slow but correct program is better than a fast and incorrect program). There are other advantages to using iterators though, such as being able to change the underlying container to one with no operator[] without modifying your loops. See this question for more.
const_iterators will most likely have none, or negligable, performance difference compared to ordinary iterators. They are designed to improve the correctness of your program by preventing modifying things that shouldn't be modified, not for performance. The same goes for the const keyword in general.
In short, optimisation should not be a concern of yours until two things have happened: 1) you have noticed it runs too slowly and 2) you have profiled the bottlenecks. For 1), if it ran ten times slower than it could, but is only ever run once and takes 0.1ms, who cares? For 2), make sure it's definitely the bottleneck, otherwise optimising it will have nearly no measurable effect on performance!
|
2,524,737 | 2,524,933 | Fixed-size floating point types | In the stdint.h (C99), boost/cstdint.hpp, and cstdint (C++0x) headers there is, among others, the type int32_t.
Are there similar fixed-size floating point types? Something like float32_t?
| Nothing like this exists in the C or C++ standards at present. In fact, there isn't even a guarantee that float will be a binary floating-point format at all.
Some compilers guarantee that the float type will be the IEEE-754 32 bit binary format. Some do not. In reality, float is in fact the IEEE-754 single type on most non-embedded platforms, though the usual caveats about some compilers evaluating expressions in a wider format apply.
There is a working group discussing adding C language bindings for the 2008 revision of IEEE-754, which could consider recommending that such a typedef be added. If this were added to C, I expect the C++ standard would follow suit... eventually.
|
2,524,816 | 2,524,898 | Creating and Compiling a C++ project on Windows | I need to work on C++ project on my windows machine. My project will consist of various classes(.h and .cpp) as well as the startup file to start the application. The preliminary design is simple but the application has the potential to gain complexity as time goes by. What I need here is ideas to set up the C++ project compiler/IDE/Makefile etc..etc. as well as some standard tools besides Visual C++ to compile/build/link projects such as these on a Windows OS.
Thanks
| I've used mingw and netbeans to develop on Windows. I chose Netbeans because it isn't excessively complicated to learn and is cross platform. I didn't like eclipse because it was in my opinion overly complex and the debugger didn't work for me in windows.
|
2,525,035 | 2,526,586 | Is there any lib for crossplatform Camera like devices streams parsing? | C\C++ lib for cross-platform device streams capturing (It shall find all devices in system and be able to give me their streams for encoding or filtering or any thing else). I want it to be cross-platrorm So is there any lib like this, opensource?
| Not sure if it meets your requirements, but what you ask sounds close to GStreamer.
|
2,525,081 | 2,525,102 | Any software to auto generate doxygen comment blocks? | I'm developing a large C++ program and I've now decided to document it with Doxygen.
There are plenty of classes, methods, functions, macros and so on. Therefore I'm searching for software that would scan my source tree and insert Doxygen comment blocks on top of every "documentable item" to let me edit them later and add details such as method descriptions and so on.
Does any such software exist?
I'm under GNU/Linux with the Code::Blocks IDE, so no Visual Studio plugins are needed.
| You can set Doxygen to extract non-documented items as well - that may do what you want without adding ANY comment blocks to the code yet.
After that you can create templates / macros (depends on your IDE) to create pre-formatted blocks for each type of item, as you slowly work through the code documenting items one by one.
[edit]
If you're using Visual Studio, some introspection is available on the classes and other constructs in the file, that may help. Alternatively take a look at Doxycomment - it might be some of what you want.
|
2,525,087 | 2,525,573 | Is it possible to find the KNN for a node that is *IN* the KD-tree? | Trying to create a KNN search using a KD-tree. I can form the KD-tree fine (or at least, I believe I can!). My problem is that I am searching to find the closest 2 neighbours to every point in a list of points.
So, is there a method to find the K nearest neighbours to a point using a KD tree even if the point is actually IN the tree, or do I need to construct a seperate KD tree for each point, leaving out the point that I wish to search for?
My implementation language is C++, but I am more looking for either an algorithm or general help, thanks!
Thanks,
Stephen
| If you want the K exact nearest-neighbors within your tree, just query the tree for K+1 neighbors (obviously since the first nearest neighbor will be your query).
|
2,525,172 | 2,525,209 | Custom "Very Long Int" Division Issue | So, for a very silly project in C++, we are making our own long integer class, called VLI (Very Long Int). The way it works (they backboned it, blame them for stupidity) is this:
User inputs up to 50 digits, which are input as string.
String is stored in pre-made Sequence class, which stores the string in an array, in reverse order.
That means, when "1234" is input, it gets stored as [4|3|2|1].
So, my question is this: How can I go about doing division using only these arrays of chars?
If the input answer is over 32 digits, I can't use ints to check for stuff, and they basically saying using long ints here is cheating.
Any input is welcome, and I can give more clarification if need be, thanks everyone.
| Implement the long division algorithm you learned in grade school.
Start by implementing subtraction. Create a function which can string-subtract any number from the input. Then you should be able to detect whether the result is negative. Modify this function to allow the number to be string-shifted before you subtract…
|
2,525,183 | 2,525,185 | How many arguments does main() have in C/C++ | What numbers of arguments are used for main? What variants of main definition is possible?
| C++ Standard: (Source)
The C++98 standard says in section 3.6.1.2
It shall have a return type of type
int, but otherwise its type is
implementation-defined. All
implementations shall allow both the
following definitions of main: int
main() and int main(int argc, char*
argv[])
Commonly there are 3 sets of parameters:
no parameters / void
int argc, char ** argv
int argc, char ** argv, char ** env
Where argc is the number of command lines, argv are the actual command lines, and env are the environment variables.
Windows:
For a windows application you have an entry point of WinMain with a different signature instead of main.
int WINAPI WinMain(
__in HINSTANCE hInstance,
__in HINSTANCE hPrevInstance,
__in LPSTR lpCmdLine,
__in int nCmdShow
);
OS X: (Source)
Mac OS X and Darwin have a fourth parameter containing arbitrary OS-supplied information, such as the path to the executing binary:
int main(int argc, char **argv, char **envp, char **apple)
|
2,525,277 | 2,525,837 | c++ templates: problem with member specialization | I am attempting to create a template "AutoClass" that create an arbitrary class with an arbitrary set of members, such as:
AutoClass<int,int,double,double> a;
a.set(1,1);
a.set(0,2);
a.set(3,99.7);
std::cout << "Hello world! " << a.get(0) << " " << a.get(1) << " " << a.get(3) << std::endl;
By now I have an AutoClass with a working "set" member:
class nothing {};
template < typename T1 = nothing, typename T2 = nothing, typename T3 = nothing,
typename T4 = nothing, typename T5 = nothing, typename T6 = nothing>
class AutoClass;
template <>
class AutoClass<nothing, nothing, nothing,
nothing, nothing, nothing>
{
public:
template <typename U> void set(int n,U v){}
};
template < typename T1, typename T2, typename T3,
typename T4, typename T5, typename T6>
class AutoClass: AutoClass<T2,T3,T4,T5,T6>
{
public:
T1 V;
template <typename U> void set(int n,U v)
{
if (n <= 0)
V = v;
else
AutoClass<T2,T3,T4,T5,T6>::set(n-1,v);
}
};
and I started to have problems implementing the corresponding "get". This approach doesn't compile:
template < typename T1, typename T2, typename T3,
typename T4, typename T5, typename T6>
class AutoClass: AutoClass<T2,T3,T4,T5,T6>
{
public:
T1 V;
template <typename U> void set(int n,U v)
{
if (n <= 0)
V = v;
else
AutoClass<T2,T3,T4,T5,T6>::set(n-1,v);
}
template <typename W> W get(int n)
{
if (n <= 0)
return V;
else
return AutoClass<T2,T3,T4,T5,T6>::get(n-1);
}
template <> T1 get(int n)
{
if (n <= 0)
return V;
else
return AutoClass<T2,T3,T4,T5,T6>::get(n-1);
}
};
Besides, it seems I need to implement get for the <nothing, nothing, nothing, nothing, nothing, nothing> specialization. Any Idea on how to solve this?
| First of all, I prefer Boost.Fusion to Boost.Tuple as it supports a better mixin of template metaprogramming and runtime algorithms I think.
For example, I'd like to present you a little marvel:
struct Name {}; extern const Name name;
struct GivenName {}; extern const GivenName givenName;
struct Age {}; extern const Age age;
class Person
{
public:
template <class T>
struct value
{
typedef typename boost::fusion::result_of::at_key<data_type const,T>::type type;
};
template <class T>
struct has
{
typedef typename boost::fusion::result_of::has_key<data_type,T>::type type;
};
template <class T>
typename value<T>::type
get(T) { return boost::fusion::at_key<T>(mData); }
template <class T>
Person& set(T, typename value<T>::type v)
{
boost::fusion::at_key<T>(mData) = v; return *this;
};
private:
typedef boost::fusion::map <
std::pair<Name, std::string>,
std::pair<GivenName, std::string>,
std::pair<Age, unsigned short>
> data_type;
data_type mData;
};
It's really fun to use:
Person p;
p.set(name, "Rabbit").set(givenName, "Roger").set(age, 22);
Well, I myself prefer indexing by classes than by indices, because I can convey meaning as well as adding type checking ;)
|
2,525,352 | 2,525,418 | Problem of using cin twice | Here is the code:
string str;
cin>>str;
cout<<"first input:"<<str<<endl;
getline(cin, str);
cout<<"line input:"<<str<<endl;
The result is that getline never pauses for user input, therefore the second output is always empty.
After spending some time on it, I realized after the first call "cin>>str", it seems '\n' is still stored in cin (using cin.peek() to check), which ends getline immediately. The solution will be adding one more line between the first usage and the second one:
cin.ignore(numeric_limits::max(), '\n');
However, I still don't understand, why is '\n' left there after the first call? What does istream& operator>> really do?
| Good writeup that explains some of the reasons why you are running into this issue, primarily due to the behavior of the input types and that you are mixing them
|
2,525,869 | 2,525,931 | Declaring STL Data Structures such as Vector in the .h | I am trying to declare a private Data Structure such as the Vector in my C++ header file which I want to eventually use within the method implementation of my .cpp.
An example would be my header "SomeClass.h" where I have:
class SomeClass
{
private:
Vector<T> myVector;
public:
void AddTtoMyVector(T add);
}
And in my .cpp which is "SomeClass.cpp", I have the following:
#include "SomeClass.h"
SomeClass::AddTtoMyVector(T add)
{
myVector.Push_back(add);
}
Would the syntax here work? Or is there a different way of declaring and populating such structures?
| Be sure to specify that you're using STL's vector, using either
std::vector<T> myVector;
or
using std::vector;
Also, if T is a generic type, you want to make the whole class templated:
#include <vector>
using std::vector;
template< typename T >
class SomeClass
{
private:
vector<T> myVector;
public:
void AddTtoMyVector(T add) {myVector.push_back( add );}
}
|
2,525,984 | 2,526,093 | Template access of symbol in unnamed namespace | We are upgrading our XL C/C++ compiler from V8.0 to V10.1 and found some code that is now giving us an error, even though it compiled under V8.0. Here's a minimal example:
test.h:
#include <iostream>
#include <string>
template <class T>
void f()
{
std::cout << TEST << std::endl;
}
test.cpp:
#include <string>
#include "test.h"
namespace
{
std::string TEST = "test";
}
int main()
{
f<int>();
return 0;
}
Under V10.1, we get the following error:
"test.h", line 7.16: 1540-0274 (S) The name lookup for "TEST" did not find a declaration.
"test.cpp", line 6.15: 1540-1303 (I) "std::string TEST" is not visible.
"test.h", line 5.6: 1540-0700 (I) The previous message was produced while processing "f<int>()".
"test.cpp", line 11.3: 1540-0700 (I) The previous message was produced while processing "main()".
We found a similar difference between g++ 3.3.2 and 4.3.2. I also found in g++, if I move the #include "test.h" to be after the unnamed namespace declaration, the compile error goes away.
So here's my question: what does the Standard say about this? When a template is instantiated, is that instance considered to be declared at the point where the template itself was declared, or is the standard not that clear on this point? I did some looking though the n2461.pdf draft, but didn't really come up with anything definitive.
| This is not valid C++ code. TEST is not dependent on the template parameter T, so it must be found in the context of the template definition when it's parsed. However, in that context no declaration of TEST exists, and so there is an error.
The diagnostic message for that ill-formed template can be delayed until instantiation by the compiler, but if the compiler is good, it will diagnose the error earlier. Compilers that don't give any diagnostic message for that code even when the template is instantiated are not conforming. It has nothing to do with unnamed namespaces.
In addition, notice that even if you put the unnamed namespace above that template, it will not be a valid C++ program either if you define and call that template in multiple translation units. This is because different instantiations of the same template with the same template arguments will refer to different things (the string in the unnamed namespace will produce a different object each time it's defined in another translation unit). Behavior for such a program would be undefined.
|
2,526,044 | 2,526,060 | Why is sizeof giving me this result? | I have this code
struct Student {
char name[48];
float grade;
int marks[10,5];
char gender;
};
Student s;
Now I have to get the sizeof s
so I added
printf("%d",sizeof(s));
now when I hit compile the result showing is 256
and its wrong because it shoud be 253
as because the size of
char name[48]; ----> 48
and
float grade; -----> 4
and
int marks[10,5]; ------> 200
and
char gender; ------->1
so 48+4+200+1 = 253
so why is it telling me 256?
================================
this part is written after I saw your answers
I learned that
Suppose I have this structure:
struct {
char a[3];
short int b;
long int c;
char d[3];
};
So ..
+-------+-------+-------+
| a |
+-------+-------+-------+
| b |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d |
+-------+-------+-------+
In the packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers willpad'' the structure (as if with extra, invisible fields) like this:
+-------+-------+-------+-------+
| a | pad1 |
+-------+-------+-------+-------+
| b | pad2 |
+-------+-------+-------+-------+
| c |
+-------+-------+-------+-------+
| d | pad3 |
+-------+-------+-------+-------+
so if Im having the maximum size is 200 should the padding be like
48 + 152
4 + 196
200 + 0
1 + 199
to make them in a perfect shape
| There may be padding bytes between the members of the struct or at the end of the struct.
In this case, it is likely that there are three bytes of padding at the end of the struct, after the single char member, to ensure that the size of the struct is a multiple of four.
|
2,526,227 | 2,528,383 | C/C++ RPC Tutorial for Linux | Can someone point me to a decent RPC tutorial for (or books) linux, like in this post. I tried looking around myself, I've only found tutorials that are really old.
Thanks
| Since the idea of RPC goes back to 1976 and the first business use was by Xerox in 1981, I'm not exactly sure what qualifies as a really old tutorial.
Here are a few resources you might find helpful.
Power Programming with RPC (1992)
Remote Procedure Calls | Linux Journal (Oct 01, 1997)
Remote Procedure Calls (RPC) (1999)
Remote Procedure Call Programming Guide (PDF link)
rpc(3) - Linux man page
|
2,526,343 | 2,526,370 | Initializing an array before initializing a pointer to that same array | I want to initialize an array and then initialize a pointer to that array.
int *pointer;
pointer = new int[4] = {3,4,2,6};
delete[] pointer;
pointer = new int[4] = {2,7,3,8};
delete[] pointer;
How can I do this?
| Why not use
int array[4] = {3, 4, 2, 6};
Is there a reason you want to allocate memory for the array from heap?
Suggestion after comment:
int arrays[32][4] = {{3, 4, 2, 6}, {3, 4, 1, 2}, ...}
int *pointers[4];
pointers[0] = arrays[0];
pointers[1] = arrays[12];
pointers[2] = arrays[25];
pointers[3] = arrays[13];
...
pointers[0] = arrays[13];
pointers[1] = arrays[11];
pointers[2] = arrays[21];
pointers[3] = arrays[6];
|
2,526,483 | 2,875,317 | Gamma Distribution in Boost | I'm trying to use the Gamma distribution from boost::math but it looks like it isn't possible to use it with boost::variate_generator. Could someone confirm that? Or is there a way to use it.
I discovered that there is a boost::gamma_distribution undocumented that could probably be used too but it only allows to choose the alpha parameter from the distribution and not the beta.
Thanks!
| As mentioned in this link, you can extend Boost's (or TR1's) one-parameter gamma distribution simply by multiplying the output of the rng by your desired scale.
Below is sample code that uses variate_generator to draw numbers from a gamma distribution, parameterized by mean and variance:
#include <boost/random.hpp>
#include <boost/random/gamma_distribution.hpp>
double rgamma( double mean, double variance, boost::mt19937& rng ) {
const double shape = ( mean*mean )/variance;
double scale = variance/mean;
boost::gamma_distribution<> gd( shape );
boost::variate_generator<boost::mt19937&,boost::gamma_distribution<> > var_gamma( rng, gd );
return scale*var_gamma();
}
|
2,526,536 | 2,526,757 | Can anyone explain what features of the C runtime in Android (via NDK) are not supported? | More specifically, does NDK have a complete STL implementation. We're looking at this for devices running 1.6 and upwards.
| No, the only supported libraries in the NDK at this time are:
libc
libm
libz (Zlib compression)
liblog (Android logging)
OpenGL ES 1.1 and OpenGL ES 2.0 (3D graphics libraries)
Also available are interfaces for JNI and minimal C++ support.
|
2,526,711 | 2,526,739 | Class declaration confusion - name between closing brace and semi-colon | class CRectangle {
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
In this example, what does 'rect' after the closing brace and between the semi-colon mean in this class definition? I'm having trouble finding a clear explanation. Also: Whatever it is, can you do it for structs too?
| rect is the name of a variable (an object in this case).
It is exactly as if it had said:
int rect;
except instead of int there is a definition of a new type, called a CRectangle. Usually, class types are declared separately and then used as
CRectangle rect;
as you are probably familiar with, but it's perfectly legal to declare a new type as part of a declaration like that.
And yes, it works for structs:
struct SRectangle { int x, y; } rect;
In fact you don't even have to give the type a name if you don't plan to use it again:
struct { int x, y; } rect;
that's called an "anonymous struct" (and it also works for classes).
|
2,526,862 | 2,526,883 | Tutorials and Introductions to C++ Expression Templates | What are good introductions to the creation of C++ expression template systems? I would like to express arithmetic on user defined types while avoiding temporary values (which may be large), and to learn how to do this directly rather than applying an existing library.
I have found Todd Veldhuizen's original paper and an example from the Josuttis C++ Templates book, and an article by Kreft & Langer. It is mentioned in Lecture 6 of a course on Modern C++, referring back to Josuttis.The POOMA library background introduces expression templates nicely.
I am looking for simple, clear expositions.
| You should get a copy of C++ Templates: The Complete Guide.
The code example to which you link doesn't have the accompanying text, which is quite helpful (the chapter on expression templates is 22 pages long). Without the text, all you have is code without any comments or explanation as to what it does and how and why it does it.
|
2,526,933 | 2,526,948 | Embed timestamp in object code at compile time with C++ | I want to perform a printf() to display when the currently executing code was last compiled. Does C/C++ provide a macro that gives you that resolves to a timestamp during compilation?
| You could use __DATE__ and __TIME__.
|
2,527,290 | 2,527,319 | Visualizing volume of PCM samples | I have several chunks of PCM audio (G.711) in my C++ application. I would like to visualize the different audio volume in each of these chunks.
My first attempt was to calculate the average of the sample values for each chunk and use that as an a volume indicator, but this doesn't work well. I do get 0 for chunks with silence and differing values for chunks with audio, but the values only differ slighly and don't seem to resemble the actual volume.
What would be a better algorithem calculate the volume ?
I hear G.711 audio is logarithmic PCM. How should I take that into account ?
| Note, I haven't worked with G.711 PCM audio myself, but I presume that you are performing the correct conversion from the encoded amplitude to an actual amplitude before processing the values.
You'd expect the average value of most samples to be approximately zero as sound waveforms oscillate either side of zero.
A crude volume calculation would be rms (root mean square), i.e. taking a rolling average of the square of the samples and take the square root of that average. This will give you a postive quantity when there is some sound; the quantity is related to the power represented in the waveform.
For something better related to human perception of volume you may want to investigate the sort of techniques used in Replay Gain.
|
2,527,437 | 2,527,449 | Adding characters to string | I am currently trying to build a very basic serial shell with my arduino.
I am able to get an output from the device using Serial.read() and can get the character it has outputted, but I cannot work out how to then add that character to a longer to form the full command.
I tried the logical thing but it doesn't work:
char Command[];
void loop(){
if(Serial.available() > 0){
int clinput = Serial.read();
Command = Command + char(clinput);
}
Can anybody help? Thank You.
| Use std::string if you can. If you can't :
snprintf(Command, sizeof(Command), "%s%c", Command, clinput);
or (remeber to check that Command does not grow too much...)
size_t len = strlen(Command);
Command[len] = clinput;
Command[len + 1] = '\0';
|
2,527,697 | 2,528,102 | Problem with extern keyword in C++ | What's the difference between the following two declarations? I thought they were equivalent, but the first sample works, and the second does not. I mean it compiles and runs, but the bitmap display code shows blank. I have not stepped through it yet, but am I missing something obvious? GUI_BITMAP is a simple structure describing a bitmap. This is for VC++ 2005, but I think it fails in VC++ 2008 also. Scratching my head on this one...
Sample 1:
extern "C" const GUI_BITMAP bmkeyA_cap_active;
extern "C" const GUI_BITMAP bmkeyA_cap_inactive;
Sample 2:
extern "C"
{
const GUI_BITMAP bmkeyA_cap_active;
const GUI_BITMAP bmkeyA_cap_inactive;
};
Edit: More exploring has shown that the second example is creating the structs, while the first is referring to external structs. The second example should fail to link, since there are two variables at global scope with the same name. But it doesn't, it sends a zero filled struct to the display code which gives up. Hmmm.....
Edit 2: Running the same code through another compiler (IAR) actually failed to compile on Sample 2, with an error about missing a default constructor. So I'm guessing there is something subtle about the "extern" keyword, structs, and C++ that I don't get. If the things in extern area were functions the two samples would be identical right?
| Your linker may is silently resolving the duplicate symbols behind your back. You might get static libraries from a vendor and have to link them with your program - what is the solution for the situation where you have two such libraries and they both define a common symbol? The linker will just resolve that, choosing one or the other definition, and leaving you to deal with the fallout. How are you handling the link stage of your application? You may have better results if you link .o files directly instead of putting them into intermediate libraries before linking the final application.
This page of the ARM documentation describes the problem well - I expect similar behaviour is happening in your case:
Multiple definitions of a symbol in different library objects are not necessarily detected. Once the linker has found a suitable definition for a symbol it stops looking for others. Assuming the object containing the duplicate symbol is not loaded for other reasons no error will occur. This is intentional and particularly useful in some situations.
Edit: More searching has turned up that this problem is caused because of a violation of the "One Definition Rule", and as a result the compiler/linker aren't required to inform you of the problem. That makes your question a duplicate of this one.
|
2,527,720 | 2,527,741 | Confused about C++'s std::wstring, UTF-16, UTF-8 and displaying strings in a windows GUI | I'm working on a english only C++ program for Windows where we were told "always use std::wstring", but it seems like nobody on the team really has much of an understanding beyond that.
I already read the question titled "std::wstring VS std::string. It was very helpful, but I still don't quite understand how to apply all of that information to my problem.
The program I'm working on displays data in a Windows GUI. That data is persisted as XML. We often transform that XML using XSLT into HTML or XSL:FO for reporting purposes.
My feeling based on what I have read is that the HTML should be encoded as UTF-8. I know very little about GUI development, but the little bit I have read indicates that the GUI stuff is all based on UTF-16 encoded strings.
I'm trying to understand where this leaves me. Say we decide that all of our persisted data should be UTF-8 encoded XML. Does this mean that in order to display persisted data in a UI component, I should really be performing some sort of explicit UTF-8 to UTF-16 transcoding process?
I suspect my explanation could use clarification, so I'll try to provide that if you have any questions.
| Windows from NT4 onwards is based on Unicode encoded strings, yes. Early versions were based on UCS-2, which is the predecessor of UTF-16, and thus does not support all of the characters that UTF-16 does. Later versions are based on UTF-16. Not all OSes are based on UTF-16/UCS-2, though. *nix systems, for instance, are based on UTF-8 instead.
UTF-8 is a very good choice for storing data persistently. It is a universally supported encoding in all Unicode environments, and it is a good balance between data size and loss-less data compatibility.
Yes, you would have to parse the XML, extract the necessary information from it, and decode and transform it into something the UI can use.
|
2,527,739 | 2,527,787 | Newbie questions about COM | I am quite new to COM so the question may seem naive.
Q1. About Windows DLL
Based on my understanding, a Windows DLL can export functions, types(classes) and global variables. Is this understanding all right?
Q2. About COM
My naive understanding is that: a COM DLL seems to be just a new logical way to organize the functions and types exported by a standard Windows DLL. A COM DLL exports both functions such as DllRegisterServer() and DllGetClassObject(), and also the Classes which implements the IUnknown interface. Is this understanding all right?
Q3. *.def & *.idl
*.def is used to define the functions exported by a Windows DLL in the traditional way, such as DllGetClassObject().
*.idl is used to define the interface implemented by a COM coclass.
Thanks in advance.
| Think of COM as a binary compatible way to share interfaces across DLL boundaries. C++ classes can't easily be exported from DLLs because of the non-standard name mangling done between various compiler versions. COM allows code in one DLL or executable, to create an implementation of an interface from another DLL or EXE as long as that implementation follows a defined interface and calling convention. This is what allows a COM class to be written in C# and invoked from C++, Python, and many other COM-aware languages.
COM interfaces are just standard C++ classes containing all pure virtual functions and derived from IUnknown. IUnknown is a pre-defined interface that all compliant COM interfaces must derive from that provides common facilities like reference counting and the ability to query whether an object implements a particular interface.
DLLs that wish to advertise the fact they can create implementations of COM interfaces do so by exporting 4 functions:
DllGetClassObject => Return a class factory of a requested interface
DllCanUnloadNow => Whether all instances handed out have since been released
DllRegisterServer => Register the types this DLL supplies in the registry
DllUnregisterServer => Unregister this DLL and its types from the registry
So to answer your questions:
Q1. About Windows DLL Based on my understanding, a Windows DLL can export functions,
types(classes) and global variables. Is this understanding all right?
DLLs can export functions and classes (not sure about global variables, but you don't want to be exporting them DLLs even if you can! :-) ) However, exported classes will be name mangled and hence only usable by other DLLs or EXEs that happen to have the same name mangling (not a good way to do business). Functions with C-style calling convention are not name mangled and hence can be exported and called from elsewhere without problems.
Q2. A COM DLL exports both functions such as DllRegisterServer() and DllGetClassObject(),
and also the Classes which implements the IUnknown interface. Is this understanding all
right?
Halfway, there are 4 functions to export to be a full COM compliant DLL (shown above). You can search MSDN for any of those names to see the full signatures fro them. Your implementation for DllGetClassObject is going to be the main one which outside parties will use. They can use that to get an IClassFactory to an interface your DLL provides, and then use that to create an instance.
COM is a large and complicated beast, but its foundations are fairly straightforward. You can also check out this link COM Intro for some more info. Good luck!
|
2,527,778 | 2,529,930 | Insert character infront of each word in a string using C++ | I have a string, for example; "llama,goat,cow" and I just need to put a '@' in front of each word so my string will look like "@llama,@goat,@cow", but I need the values to be dynamic also, and always with a '@' at the beginning.
Not knowing a great deal of C++ could someone please help me find the easiest solution to this problem? Many thanks in advance.
| Judging by insertable's comments, (s?) he's trying to get this code working... So let me offer my take...
As with the others, I'm presuming each word is delimited by a single ",". If you can have multiple character delimiters, you'll need to add a second find (i.e. find_first_not_of) to find the start/end of each word.
And yes, you could insert the '@' characters into the preexisting string. But inserting for each word gets a little inefficient (O(N^2)) unless you're clever. That sort of cleverness usually comes with a high maintenance/debugging cost. So I'll just stick to using two strings...
(There ought to be some brilliant way to do this with STL algorithms. But I'm sick and I just don't see how to accommodate insertion right now...)
References: C++-strings C++-strings STL count_if
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define SHOW(X) cout << # X " = " << (X) << endl
int main()
{
// 0123456789_123456789_1234
string inString(",llama,goat,cow,,dog,cat");
string outString;
/* This code assumes inString.size() > 0 */
const iterator_traits<string::iterator>::difference_type numberOfWords
= count_if( inString.begin(), inString.end(),
bind2nd( equal_to<char>(), ',' ) )
+ 1;
string::size_type startIndex, endIndex;
outString.reserve( inString.length() + numberOfWords );
for ( startIndex = endIndex = 0;
endIndex != string::npos;
startIndex = endIndex + 1 )
{
outString += "@";
/* No startIndex+1 here. We set startIndex=endIndex+1 in the for loop */
endIndex = inString . find_first_of( ",", startIndex );
outString . append ( inString, startIndex,
( (endIndex == string::npos)
? string::npos : endIndex - startIndex + 1) );
}
SHOW( numberOfWords );
SHOW( inString );
SHOW( outString );
SHOW( inString.size() );
SHOW( outString.size() );
SHOW( inString.capacity() );
SHOW( outString.capacity() );
}
|
2,527,780 | 2,527,797 | C++ Linker Error SDL Image - could not read symbols | I'm trying to use the SDL_Image library and I've added the .so to the link libraries list for my project (I'm using Code::Blocks, by the way).
After doing this, when I go to compile, I get this error:
Linking console executable: bin/Debug/ttfx
/usr/lib32/libSDL_image-1.2.so: could not read symbols: File in wrong format
What does this mean and how can I get it working?
Edit: I'm using gcc.
Thanks!
| During the linking step there are incompatibilities since some of your object files were compiled for 32-bit and some for 64-bit. Looking at its path libSDL_image.so was probably compiled for 32-bit.
If you use the GNU compiler add -m32 to your CXXFLAGS to compile your objects for 32-bit, too.
|
2,527,885 | 2,528,056 | Is there anything RAD comparable to VCL? | After years in embedded programming, I have to develop a Windows app. I dug out my old C++ Builder and Delphi. These are great and the latest version costs over $1k, so I won't be going there.
What I particularly like is the VCL (visual component library) which let's me code my own components and share them with others, plus the thousands of existing 3rd party components. I noticed that there is now also a RAD PHP from Borland too.
I realize that MSVC, QT, NetBeans, etc are good enough IDEs for RAD, BUT does anything offer the ease of the Borland products for developing additional components - and does anything else have thousands to choose from?
PC based? Cross-platform is good. Browser based? Free is always good ;-)
I don't particularly care about the programming language.
I went with Lazarus and am pretty happy with it. I can't just recompile my code and expect it to run, but it covers 90% of my existing Delphi code. I'd recommend giving it a whirl before spending $1k for Delphi
| Try Lazarus, Lazarus is a cross platform visual IDE for Pascal and Object Pascal developers. It is developed for and supported by the Free Pascal compiler. is available for several Linux distributions, FreeBSD, Microsoft Windows (win32/64/CE) and Mac OS X (including IPhone/IPad). The language syntax has excellent compatibility with Delphi (classes, rtti, exceptions, ansistrings, widestrings, interfaces).
for additional info check theses links
free pascal
Components and Code examples
Lazarus Components
|
2,527,951 | 2,527,957 | What does this mean: warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’ | I have a member function in a class that has a callback, but the callback isn't strictly neccessary, so it has a default callback, which is empty. It seems to work fine, but I get an annoying warning:
warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’
I'm trying to figure out what it means and how to turn it off (or fix it if I really am doing something wrong). Here's some simple code:
class ClassName{
public:
void doSomething(void (*callbackFunction)() = (void(*)()) &ClassName::doNothing){
callbackFunction();
}
void doNothing(){}
};
int main(){
ClassName x;
x.doSomething();
return 0;
}
Note: If I do this (without explicitly casting it as a void(*)()):
void doSomething(void (*callbackFunction)() = &ClassName::doNothing)
I get this:
main.cpp:3: error: default argument for parameter of type ‘void (*)()’ has type ‘void (ClassName::*)()’
| The issue is that you're passing a pointer to an instance method rather than a static method. If you make doNothing a static method (which means no implicit instance argument), the warning goes away.
Specifically,
warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’
exactly is saying that it's converting from a member function of class ClassName, to a non-member function.
See also the C++ FAQ Lite entry about pointers to member functions and pointers to functions.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.