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 |
|---|---|---|---|---|
3,866,405 | 3,866,538 | C++ Coding virtual machine | I haven't done much coding in C++, but I? noticed that I have to run these build scripts for everything. HOw do people do these on windows machines? I am thinking about running a virtual machine anyway, so I don't have to fill my machine with python and other such installations.
How does everyone else on windows do it?... | MinGw comes with a gcc-compatible Compiler and Make System. So if you want to use makefiles, this is a possible way. If you need an IDE, Eclipse CDT might be for you.
However, I prefer Visual Studio, mainly for personal reasons (experience gathered over years) and debugging seemed to work somewhat better.
You might als... |
3,866,563 | 3,866,637 | Should GUI application warning messages be sent to std::cerr? | Should a Unix GUI application's warning be sent to std::cerr or std::cout?
This presumes that GUI normally presents the warnings and errors in a console window and also sends them to a log file. But in the case that the console is missing and thus cannot be used should std::cerr, std::cout, or std::clog be used for su... | For a compiler, error messages about the code being compiled are the "normal" output, so they should be written to stdout, not stderr. The only messages that should be written to stderr would be about errors in running the compiler itself (e.g., if a file that makes up part of the compiler can't be found, so the compil... |
3,866,584 | 3,866,743 | signal processing: C++ vs C# | I would like to build my own signal processing library, and possibly another one about graphs algorithm. I find C# very useful and robust in regards of possible bugs associated with memory allocation, pointers, threading etc...
But I was wondering how much am I going to lose in terms of performance. Is it going to be s... | When I started my DSIP course I was a pure C# developer . After looking around for a while, I ended up using C++libraries and learning C++ which at end it was to my benefit since I was doing real-time image processing and there is no way C# can match the performance.
In fact, you can run a quick test and run a mathemat... |
3,866,623 | 3,866,752 | Determining whether a non-object variable is initialized in C++ | So, let's say, in a class in C++, I have a variety of member variables. Structs, strings, ints, etc. etc. Could be anything. These variables can or cannot be set by the initialization of the object of this class. Given int a, float b, char c, sometimes all of them or none of them can be set. When they are set, they can... | I would use a nullable template. See http://www.codeproject.com/KB/mcpp/CNullable.aspx
|
3,866,642 | 3,866,682 | STL list erase items |
Possible Duplicate:
Can you remove elements from a std::list while iterating through it?
I want to erase items from the list while iterating over. I have done this before, but somehow this simple example fails me. thnx for the help in advance!
#include<iostream>
#include<list>
using namespace std;
void main()
{
... | erase returns the element after the erased element: http://www.cplusplus.com/reference/stl/vector/erase/
So try something like this:
for( list<int>::iterator k = x.begin(); k != x.end();)
if( (*k)%2 )
k=x.erase(k);
else
++k;
|
3,866,715 | 3,866,775 | How do you initialize a static templated container? | I'm trying to figure out the correct way of initializing a static container variable whose template value is a private inner class. Here's a toy example
#include <vector>
using namespace std;
template <class myType>
class Foo {
private:
class Bar {
int x;
};
static vector<Bar*> bars;
};
templa... | Try this:
template <class myType>
vector<typename Foo<myType>::Bar*> Foo<myType>::bars;
|
3,866,773 | 3,866,802 | overloading the = operator with inheritance | hey i am trying to understand how to overload the operator= when there is an inheritance
with no Success.
code example:
class Person
{
private:
char* m_name;
char* m_lastName;
.....
public:
virtual Person& operator=(const Person& other);
};
/********************/
cpp im... | Your implementation is not typesafe, because I can write:
Student s;
Person p;
s = p;
And it will compile the assignment successfully, but will result in U.B. (likely segfault or garbage read) at runtime, because you downcast the right argument of operator= from Person to Student, while it is not one.
More generally, ... |
3,866,847 | 3,866,890 | Strange? behaviour of cout | Why executing this code:
// DefaultAny.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <exception>
using std::cout;
template<class T>
struct NoReturnPolicy
{
static void calculate(T& result, const T& source)
{
result = source;
}
};... | This is the result of unspecified behavior. If you have:
cout << a() << b() << c() << endl;
The order of execution of a, b, and c is not defined (yes, their results are added to the cout stream in a predictable order, but execution of the functions is not in defined order).
|
3,866,898 | 3,867,079 | Using "Static" Keyword to Limit Access in C++ Member Functions | I understand that one benefit of having static member functions is not having to initialize a class to use them. It seems to me that another advantage of them might be not having direct access to the class's not-static stuff.
For example a common practice is if you know that a function will have arguments that are not... | Static member functions should be used when they are relevant to the class but do not operate on an instance of the class.
Examples include a class of utility methods, all of which are static because you never need an actual instance of the utility class itself.
Another example is a class that uses static helper functi... |
3,867,001 | 3,867,055 | Does declaring C++ variables const help or hurt performance? | I understand the behavior of const-qualified data types. I am curious, though, if there is any performance gain or loss from over- or under-zealousness of qualifying variables as const. I am thinking particularly of variables declared and used exclusively within an isolated code block. For example, something like:
cons... | const is mainly a compile-time thing, however, declaring something as const sometimes allows for certain optimizations. If the code in question isn't a performance bottleneck, I wouldn't worry about it and just use const as intended: to produce clearer code and prevent yourself from doing stupid things.
|
3,867,068 | 3,867,831 | Portable stream-of-bytes interface for C++ | I work on an open source portable C++ image compression library. Currently, my API works by exchanging pointers to byte arrays with image data. I would like to support some kind of streaming mode for better performance and memory consumption.
For this, I would like to know if there is an interface or abstract base cla... | If your library accepts a std::istream then it will work with files, memory buffers, and user-defined streams.
Your source of confusion seems to be that istream doesn't have any virtual members to override and customize. This is because istream delegates all customizable functionality to std::streambuf, which is where... |
3,867,111 | 3,867,144 | Compare result of std::distance with an unsigned type | I wish to compare index of an element in a std::vector to an unsigned value. If I directly compare like;
if(std::distance(...)>min_distance) // true for some
I just get a warning, but works fine. However, to get rid of the warning, if I cast min_distance to int, I do not get any comparison result (although there is)
i... | Try:
if ( std::abs( std::distance( ... ) ) > min_distance )
std::distance returns a signed value. I am assuming you are trying to get the distance in such a way that -2 AND 2 would be considered as 2. The abs function gives you the absolute value which means that whatever the sign of the input, you always get a posi... |
3,867,122 | 3,867,152 | C++ and table format printing | I am looking for how to print in C++ so that table column width is fixed.
currently I have done using spaces and | and -, but as soon as number goes to double digit all the alignment goes bad.
|---------|------------|-----------|
| NODE | ORDER | PARENT |
|---------|------------|-----------|
| 0 | ... | You can use the std::setw manipulator for cout.
There's also a std::setfill to specify the filler, but it defaults to spaces.
If you want to center the values, you'll have to do a bit of calculations. I'd suggest right aligning the values because they are numbers (and it's easier).
cout << '|' << setw(10) << value << ... |
3,867,254 | 3,868,120 | What is the Microsoft Visual Studio equivalent to GCC ld option --whole-archive | When linking a static library against an executable, unreferenced symbols are normally discarded. In my case some otherwise unused objects are used to register their respective classes into a factory and if the objects are discarded, this registration fails.
Under Unix where we use gcc, I can pass the flag --whole-arch... | To my knowledge, there is no single option which reliably guarantees that. There are combinations of optimizing options which (silently) deactivate this, so no way... /INCLUDE works, but for that you need to extract and hardcode the mangled name of the symbol. You have two choices: (1) ensure, that all registrars are c... |
3,867,276 | 3,867,323 | Can the 'type' of a lambda expression be expressed? | Thinking of lambda expressions as 'syntactic sugar' for callable objects, can the unnamed underlying type be expressed?
An example:
struct gt {
bool operator() (int l, int r) {
return l > r;
}
} ;
Now, [](int l, int r) { return l > r; } is an elegant replacement for the above code (plus the necessa... | No, you cannot put it into decltype because
A lambda-expression shall not appear in an unevaluated operand
You can do the following though
auto n = [](int l, int r) { return l > r; };
std::set<int, decltype(n)> s(n);
But that is really ugly. Note that each lambda expression creates a new unique type. If afterwards y... |
3,867,391 | 3,867,417 | What's a good reference for creating and updating Performance Counters in unmanaged code? | I have several apps that need to create and write to Performance Counters. One of them is written in C++. Currently, upgrading that app to .NET is not an option. Where is a good resource for accessing Performance Counters using unmanaged code?
Thanks!
| Start here: http://msdn.microsoft.com/en-us/library/aa373209(v=VS.85).aspx
Note that how you publish the data depends on your OS: http://msdn.microsoft.com/en-us/library/aa373165(v=VS.85).aspx
|
3,867,397 | 3,867,425 | Generic structs in unions | I'm trying to make a generic vector class. While I can do something like this:
struct vector3 {
union {
struct {
float x;
float y;
float z;
};
float v[3];
};
};
I cannot do this:
template<int N, typename S, typename T = double>
class vec {
union {
T data[N];
S;
... | You need to name the member:
template<int N, typename S, typename T = double>
class vec {
union {
T data[N];
S you_need_to_have_a_member_name_here;
};
};
struct XY { REAL x, y; };
typedef vec<2, XY, REAL> Vector2;
But more importantly, what exactly are you trying to accomplish? If you want a h... |
3,867,633 | 3,867,953 | Is there any setfill() alternative for C? | In C++:
int main()
{
cout << setfill('#') << setw(10) << 5 << endl;
return 0;
}
Outputs:
#########5
Is there any setfill() alternative for C? Or how to do this in C without manually creating the string?
| No, there is no direct alternative.
But if you have a well-behaved snprintf (one that behaves as described by the C99 Standard), this works without creating a new string; creating only 2 temporary ints
#include <stdio.h>
int main(void) {
int filler = '#'; /* setfill('#') */
int width = 10; /* setw(10) */
i... |
3,867,947 | 3,868,016 | Why is my program slow ? How can I improve its efficiency? | I've a program that does Block Nested loop join (link text). Basically what it does is, it reads contents from a file (say 10GB file) into buffer1 (say 400MB), puts it into a hash table. Now read contents of the second file (say 10GB file) into buffer 2 (say 100MB) and see if the elements in buffer2 are present in the ... | The running time for your program is (l1 x bs1 x l2 x bs2) (where l1 is the number of lines in the first file, and bs1 is the block size for the first buffer, and l2 is the number of lines in the second file, and bs2 is the block size for the second buffer) since you have four nested loops. Since your block sizes are c... |
3,867,948 | 3,868,915 | Trying to compile a working irrlicht application on a mac with plain g++ or Xcode | Ok, here it goes:
I managed to compile the .xcodeproj provided with the last zip achive into a .a library file (a static library then).
I failed to build a working application that uses irrlicht as a 3D engine with Xcode, I don't really know to do it since I'm sort of unable to use an IDE.
I tried to link a simple prog... | The irrlicht SDK comes with the .xcodeproj project file bundle. You already successfully compiled it; it also contains the project for the sample codes. Try compiling the example 01, "Hello world." Don't forget to change EDT_SOFTWARE with EDT_OPENGL; otherwise the sample program will horribly slow-down your system!
Ca... |
3,868,106 | 3,868,172 | Does an approximation of C++'s "const methods" exist for Objective-C? | Wondering if there's any accepted practice for approximating C++'s 'const methods' in Objective-C. (new to the language from a C/C++ background)
For instance:
class Foo {
public:
void canChangeMemberVars(void);
char* asString(void) const;
};
"asString()" gets a const this pointer, so even if you go rogue ... | Yes, your only option if you want to have a class that sometimes can be mutated and sometimes can't is to make mutable and immutable versions of the class. You'll notice this is how Apple does it in Cocoa (NSArray, NSSet, NSDictionary, NSString, etc.) — following Apple's conventions is usually the best way to go.
Objec... |
3,868,215 | 3,868,279 | string reverse in c++ | Why does this piece of code throw an exception when I try to change a character in the string
void reverseString(char *s)
{
int e = strlen(s) - 1;
int b = 0;
char t1,t2;
while(b < e)
{
t1 = s[b];
t2 = s[e];
s[b] = t2;
s[e] = t1;
b++;
e--;
}
}
| My guess is that the string you are testing it on is stored in read-only memory. Did you define it with a string literal?
Added later to elaborate:
If you do this,
char *s = "Hello";
reverseString(s);
you will probably crash, because the string can be stored in read-only memory, and most compilers will put it there.
... |
3,868,287 | 3,868,318 | Is a std::vector pointer reliable? | Say I have this:
Object *myObject;
std::vector<Object> objects(99);
....
myObject = &objects[4];
Would it be safe to assume that myObject's pointer will always be valid no matter how big objects[] gets and if I remove some, as long as I do not ever erase() the actual object pointed to by myObject? Or does it work dif... | If the vector fills up its allocated space and you try to insert more, it needs to re-allocate its storage, and that will involve copying over the objects and destroying the old storage, which would invalidate the pointer you're keeping around - so no, this is not good enough.
std::list would work fine, since it doesn'... |
3,868,334 | 3,868,421 | c++ member function specialisation of a class that has a template as a parameter | I am working on a template class Array, which accepts another template TRAITS as a parameter.
template <typename BASE, typename STRUCT>
class Traits {
public:
typedef BASE BaseType;
typedef STRUCT Struct;
// .. More here
};
template <class TRAITS>
class Array {
public:
... | if I know correctly, you had to specialize entire class.
instead of doing that, I create specialized functions parameterized for particular class:
For example:
Struct& operator[](size_t i)
{
return operator_(i, boost::type<TRAITS>());
}
private:
template<class B>
Struct& operator_(size_t i, ... |
3,868,810 | 3,875,427 | Visual Studio Breakpoint Macro to modify a value? | I'm debugging an application (C++), and I've found a point in the code where I want to change a value (via the debugger). So right now, I've got a breakpoint set, whereupon I do:
Debugger reaches breakpoint
I modify the variable I want to change
I hit F5 to continue running
lather, rinse, repeat
It's hitting this br... | I found how to do this with a macro. Initially, I tried using Ctrl-Shift-R to record a macro of keystrokes, but it stopped recording when I did Ctrl-Alt-Q. But I was able to edit the macro to get it to work. So here's what I did, in case anyone else wants to do something similar.
Tools -> Macros -> Macro Explorer
R... |
3,868,827 | 3,868,844 | How do pointers to pointers and the address-of operator work? | Take this piece of code:
int a;
int *pointer = &a;
int **b = &(&(*pointer));
Would the above set b to the address of pointer or not?
The reason I ask is because *pointer gives the value of a, and the reference of that is the address of a. Is this treated as just the address of a, or is it also treated as pointer.
Doe... | No. In C, you can only get a pointer to a storage area (which means a variable, an array element, or another pointer; they call those "l-values"), not to any expression. You cannot get a pointer to an expressions that has no defined storage area (like an addition, or the result of a function call). It should be noted h... |
3,868,883 | 3,869,297 | Help with this (pointers and polymorphism) | Here is my issue.
I'm creating my own GUI Api. All the Widgets are in a container which has add and remove functions. The widgets derive from a base widget class. Here is where I'm unsure. I would ideally like a flow like this:
user creates a (desired widget deriving from base class) pointer, the container allocates an... |
My other quick-fix alternative is to
make the user responsible for doing
the new, and providing the pointer to
the container's add function. But this
does not feel idiot proof to me, and
it seems odd to have the user do the
initial allocation, but then the
container manages the rest including
erasure.
... |
3,868,886 | 3,869,251 | Readers/writers and decoupled persistence of derived classes | I'm refactoring a bunch of old code. My primary objective is to decouple the behavior from the database. The current implementation accesses the database directly which makes it hard to test and do things like implement caching layers etc... Up until this point I've been using a combination of dependency inversion a... | Here's a sample using the double dispatch implementation specified in the wikipedia page:
#include <iostream>
using namespace std;
class Writer;
class User
{
public:
std::string name() const { return m_name; }
void name(const std::string& name) { m_name = name; }
virtual void accept(Writer & writer) const... |
3,868,938 | 3,868,967 | AST for any arbitrary programming language or IR | Is it possible to create an AST for any arbitrary programming language or IR using C or C++ alone (without the help of tools like YACC and LEX )?
If so, how to implement the lexical and syntactic analysis ?
If not, what are the tools that have to augmented to C or C++ to successfully create an AST ?
Hope I made my doub... | The most straight-forward methodology for creating the parser without a parser-generator is recursive descent. It is very well documented - the standard book in the field is The Dragon Book.
A scanner, that takes text as input and produces a string of tokens as output, can be written using standard string manipulation... |
3,869,053 | 3,869,155 | Game File Archive Format | I want to create a single data file that holds all the data that my game will need, and I want it to be compressed. I looked into tar and gzip, but I downloaded their sources and I don't know where to begin. Can somebody give me some pointers to how I can use these?
| Unless you will always load all files from the archive, TAR/GZ might not be a very good idea, because you cannot extract specific files as you need them. This is the reason many games use ZIP archives, which do allow you to extract individual files as required (a good example is Quake, whose PK3 files are nothing but Z... |
3,869,078 | 3,869,119 | Trouble with char* and char** (C --> C++) | Okay, I am trying to integrate some C code into a C++ project, and have run into a few problems. I will detail the first one here.
I keep running into this error:
error: cannot convert 'char*' to 'char**' in assignment|
here is the offending code (with the breakpoint marked):
char** space_getFactionPlanet( int *nplanet... | If you're converting to C++, then let's do away with the malloc shall we?
tmp = new char*[mtmp];
But later on, you will probably find something like this:
free(tmp);
Which you need to change to this:
delete [] tmp;
If tmp is returned from the function, do not delete it. You need to trace the pointer. Somewhere, pe... |
3,869,084 | 3,918,909 | Iterate over items in Boost Property Tree | I'm using boost property tree to store configuration data for my application.
In the configuration file I have an item named that looks like this.
I'm wondering how I can iterate over the ServerList.
ServerList
{
server1 127.0.0.1:5000
server2 example.com
}
By the way the solution provided here, didn't seem to w... | To answer my own question. The clue is in the error.
I'm using a wiptree here
invalid initialization of reference of type ‘boost::property_tree::wiptree& ...
But a basic ptree here
type ‘boost::property_tree::basic_ptree ...
Change from wiptree to ptree and it works.
|
3,869,144 | 3,869,156 | How can I read multiple bytes from a file at a time? | I want to read 8byte chunks from a binary file at a time till I reach end of the file. Why doesn't this code work? What are the alternatives?
// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long long int * buffer;
ifstream is;
is.open ("test.txt", ios::binar... | The problem is !eof: it tells you whether the last operation hit eof, not whether the next will, and not whether the last failed!
Test the stream's truthiness itself (or use the fail method which is the same thing, negated), after doing the IO:
while (is.read(buffer, sizeof(long long int))) {
// use buffer
}
assert(i... |
3,869,211 | 3,869,235 | Replacing realloc (C --> C++) | In an earlier question, I asked about typecasting pointers, but was directed to the better solution of using the C++ allocation system instead of mallocs. (I am converting some C code to C++)
However, I still have an issue with a similar function:
I changed:
tmp = malloc(sizeof(char*) * mtmp); --> tmp = new char*[mtmp]... | C allows void* to be implicitly converted to any pointer. C++ doesn't, so if you're using realloc, you have to cast the result to the appropriate type.
But more importantly, using realloc on a pointer returned by new[] is undefined behavior. And there's no direct C++-style equivalent to realloc.
Your choices are, fro... |
3,869,253 | 3,869,316 | Seeing console output without console? | I'm making an application and would like to test the toString method I just made. I'm using Visual c++ 2008. Is there a way to see console output without having a console window? Such as in the Output panel?
Thanks
| If you call OutputDebugString, it will display the string in the output window when you run the program under VS++. Most other debuggers (and a number of other monitoring applications and such) can/will display such strings as well, but when you run the program without a debugger (or something similar) that output will... |
3,869,567 | 3,869,773 | Why does this reject an enum? | Why does this code fail?
#include <algorithm>
int main() {
int a[10];
enum { a_size = sizeof a / sizeof *a };
std::fill(a, a + a_size, a_size);
}
G++ 4.1.2 and 4.4.3:
In function 'int main()':
Line 5: error: no matching function for call to 'fill(int [10], int*, main()::<anonymous enum>)'
Is this code valid ... | std::fill is parameterized on the type of its object argument; it does not require an argument of Iterator::value_type. So, as In silico says, C++03 can't instantiate the template with a local type.
However, in C++0x, you can use local types to instantiate templates, because they are given external linkage.
|
3,869,570 | 3,869,589 | java vs C++ pass by reference |
I am confused in the following:
In C++ we can pass a parameter to a function by reference (having declared it as a pointer or reference variable) and if we modify it inside the function, the changes are reflected to the caller when the function returns.
This is not happening in java and I am not sure I understand why.... | Java passes everything by value - including references.
What this means is that if you pass an object, you can modify properties of that object, and they will persist after you return, but you can't replace the object in its entirety with a completely new object, because you can't actually modify the reference - only w... |
3,869,599 | 3,894,936 | Why SetMenuInfo doesn't work under Windows 7? | When I use SetMenuInfo to change background color of MenuBar it works under Windows XP,but doesn't work under Windows 7.What is the reason?How can I solve the problem?
Thanks.
| This is probably a theming issue. If you switch to classic theme, the background colour change will probably start working again but the normal default themes don't allow this option to work. I think a few controls have changed in this way with theming. I'm surprised you don't see the problem in XP though - I thought t... |
3,869,607 | 3,869,629 | Error in try catch while converting VC6 to VS2008 | When I opened a VC6 project in VS2008 and tried building it , initially I got the error:
fatal error C1083: Cannot open include file: 'iostream.h': No such file or directory
error C2259: 'CException' : cannot instantiate abstract class
error BK1506 : cannot open file '.\Debug\SClientDlg.sbr': No such file or directory... | You likely need to do this:
catch(CException& ex) // const& might be better
Since CException is abstract, you cannot instantiate it, but you can reference a non-abstract object that derives from it.
|
3,869,801 | 3,869,819 | Which alternative in C++? | One of the things about programming is that there are several ways to achieve the same goal. During my time coding in C++ I have noticed the following variations in ways to implement certain common features. My question is what are the advantages/disadvantages of each, I understand for the most part how each of them wo... | if your primarily programming lang is C++ and you are doing object oriented programming, then it is going to be cout, cin and endl - hands down :)
it is not a matter of performance, but it is more of a matter of style and coherent coding.
in addition to that you get the perks of having cout, cin work on user defined ... |
3,869,830 | 3,869,852 | Near and Far pointers | What is difference between our usual pointers(ones which we normally use), near pointers and far pointers and is there a practical usage for near and far pointers in present day C/C++ systems? Any practical scenario which necessiates use of these specific pointers and not other c,c++ semantics will be very helpful.
| The near and far keywords have their origin in the segmented memory model that Intel had before. The near pointers could only access a block of memory originally around 64Kb in size called a segment whereas the far pointers could go outside of that range consisting of a segment and offset in that segment. The near poin... |
3,869,867 | 3,878,910 | Create COM DLL from Unmanaged C++ LIB | I have followed the steps here to create a COM DLL in Visual Studio 2008. My objective is to wrap an existing unmanaged C++ .lib.
Is there an easy way to implement the COM interface for the lib. Or do I just have to keep adding ATL simple objects which essentially wrap the objects in my library?
For example, I have ad... | In order to expose your functionality to COM you'll need to perform two major steps:
introduce COM interfaces
implement those interfaces using functionality of code you already have
So yes, the scenario you described is the typical way to solve this problem.
Using ATL will simplify things a lot. However you have to t... |
3,869,963 | 3,870,137 | Compound literals in MSVC | In GCC, I'm able to do this:
(CachedPath){ino}
inode->data = (struct Data)DATA_INIT;
where:
struct CachedPath
{
Ino ino;
};
typedef int8_t Depth;
struct Data
{
Offset size;
Blkno root;
Depth depth;
};
#define DATA_INIT {0, -1, 0}
MSVC gives the following error for these kind of casts:
error C2143: sy... | The construct (Type){initialisers} is not a cast operation, but it is the syntactic construct of a compound literal.
This is a C99 construct, which GCC also supports in its C++ compiler as an extension. As far as I can determine, compound literals are not supported up to and including MSVC 2012, in either its C or C++ ... |
3,870,043 | 3,870,471 | Exception JNI (Ljava/lang/String;)Ljava/lang/String; | I have made a little program in java that accepts a string as a user input. Now i have made a dll writing its code in Visual C++. when i run my program from netbeans it displays this exception.
Exception in thread "main" java.lang.UnsatisfiedLinkError: Prompt.getLine(Ljava/lang/String;)Ljava/lang/String;
at Pro... | @org.life.java....i got the problem and it was my mistake, i was not including the header file of java which is JNI style header file which is Prompt.h in c++, "#include "jni_md.h" this will be eliminated and included "Prompt.h" now it is working fine.
|
3,870,128 | 3,870,136 | What are variadic functions in accordance with C and C++? | I am confused. As i asked the question previously about overloading in C, i got some answers.
Whenever i try to make others understand about this, I get confused in "variadic functions".
Please let me know about it with your shower of knowledge!
| In short, they are functions that accept any number of arguments.
http://en.wikipedia.org/wiki/Variadic_function
|
3,870,172 | 3,876,185 | Evaluation of a reference expression | As per @Potatoswatter's suggestion, I have created a new discussion.
Reference is this response from @Potatoswatter
Given the code snippet,
int i = 3, &j = i;
j = ++ i;
The comment which I seek clarity on, is this. (which seems to be an important missing piece in my understanding of the unsequenced evaluation a.k.a ... | Imagine the following
int &i = *new int;
If you say that i is an alias for another name - what name? A reference either references an object or function. When you say "glvalue", you refer to a property of a particular expression, not to a property of an object.
int i = 0;
int &ri = i;
Now, i is an lvalue expression ... |
3,870,201 | 3,870,574 | C++ error no such file or directory | Hey guys, I just started learning C++ and I have this code that I have to complete but the class header is giving me this error
error: string: No such file or directory
#include <vector>
#include <string>
class Inventory
{
public:
Inventory ();
void Update (string item, int amount);
void ListByName ();
... | I don't think your error is anything to do with namespaces.
You say you're getting error: string: No such file or directory which implies that the pre-compiler cannot find the STL string definition file. This is quite unlikely if you're also including vector and having no problems with that.
You should check your compi... |
3,870,327 | 3,870,458 | Unresolved symbol on DLL loadup | I am loading a DLL from an application and I want the DLL to be able to use a function implemented in the application. The definition of the function is put in a header and is included in the DLL. Can anyone tell me what I am doing wrong here or whether this can't be done? Thanks for any help.
App:
include <API.h>
ext... | You should instruct your compiler to put all the symbols of your executable (App) in it's dynamic symbol table. Otherwise, as Marcus Lindblom said, the dependencies would be one way only. With g++, the option is -rdynamic.
|
3,870,435 | 3,881,971 | Handling STL errors without exceptions | I have a project which uses STL a lot. Now I'm working on porting the project to a specific platform which doesn't support exceptions. I can disable exceptions, however I still need to handle STL errors.
Is there any approach to handle STL errors correctly with exceptions disabled? Is there any third party STL implemen... | The problem with taking an existing std library coontainer and compiling with exceptions disabled is that the the std container interfaces themselves assume exceptions are enabled. Using exceptions, operator new will throw if it cannot acquire memory, without exceptions, operator new returns a 0 instead, which std cont... |
3,870,538 | 4,104,233 | How can I force the compiler-generated copy constructor of a class to *not* be inlined by the compiler? | Alternate question title would be:
How to explicitly have the compiler generate code for the compiler-generated constructors in a specific translation unit?
The problem we face is that for one code path the resulting -- thoroughly measured -- performance is better (by about 5%) if the copy-ctor calls of one object are ... | To add my own conclusion and to answer the exact question without going into details:
You cannot force the compiler, specifically VC++, to inline or not inline a compiler-generated ctor/dtor/etc. -- but
The optimizer will choose - on its discretion - if it inlines the code for a compiler generated function (ctor) or i... |
3,870,740 | 3,870,845 | How to design a C++ API | I'm fairly new to advanced C++ program techniques such as templates,
but I am developing a simple API for a project I'm working on.
The function or method that you call can take a long time to complete.
Essentially it's transferring a file over the network.
It looks a bit like this.
Client
{
int WriteFile();
int R... | My advice would be looking at the docs and tutorial for boost::asio (which you can use as part of boost or as part of the independent asio project, but I guess that the requirement is no external libs, not just no boost).
Usually blocking calls are simple to define, while non-blocking operations require some callback m... |
3,870,772 | 11,909,483 | Cython C++ and std::string | What is the best way of using C++ standard std::string from cython? The last cython distribution should make it easy anyway, but I wonder why there are wrappers for std::vector and not for std::string...
| Cython 0.16 includes wrappers for std::string, which can be imported with:
from libcpp.string cimport string
|
3,870,863 | 3,870,883 | Is it possible to add some functionality to a class without subclassing? | In Ojective-C there is something called Categories which allow the user to add methods from outside the original .h or .m file (objective-c's version of .cpp)
I wonder if there exist such functionally in C++.?
I specially want implement << operator for debugging and maybe others of a class that is in a library I freque... | You could always overload operators outside of the class.
std::ostream& operator<< (std::ostream& f, const YourClass& cls) {
...
}
You still need to friend this function if it needs to access private members of YourClass.
(But it's not possible to define normal member functions like what Objective-C does.)
|
3,871,039 | 3,871,156 | How to overload operator==() for a pointer to the class? | I have a class called AString. It is pretty basic:
class AString
{
public:
AString(const char *pSetString = NULL);
~AString();
bool operator==(const AString &pSetString);
...
protected:
char *pData;
int iDataSize;
}
Now I want to write code like this:
AString *myString = new AString("foo");
... | No, there is not.
To overload operator==, you must provide a user-defined type as one of the operands and a pointer (either AString* or const char*) does not qualify.
And when comparing two pointers, the compiler has a very adequate built-in operator==, so it will not consider converting one of the arguments to a class... |
3,871,429 | 3,871,597 | Class members that are objects - Pointers or not? C++ | If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not? What does it mean also to have it as not a pointer in terms of where it is stored in memory? Will the object be created when the class is created?
I noticed that the examples in QT usually d... |
If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?
you should generally declare it as a value in your class. it will be local, there will be less chance for errors, fewer allocations -- ultimately fewer things that could go wrong, and the c... |
3,871,639 | 3,871,750 | How can I call a C++ dll from VS2008 | Well I have created a DLL using the Article from CP. For creating this DLL aslso, I have used VS2008. Now I am not sure how can I call this DLL from another C++ application created in VS2008. When I click on Refrences>Add New Reference this is asking for the project folder not for the DLL path.
In the Code Project art... | Are you talking about a managed DLL (.NET)? Only then you need to do the "Add New Reference" stuff.
If not:
Together with your DLL a file with the extension ".lib" has been created (the import lib).
Add it to your project of the calling application e.g. in the project settings:
"Configuration Properties" - "Linker" ... |
3,871,864 | 3,871,893 | Accessing overridden base class member from derived class object | I have two classes:
class A
{
public:
int i;
};
class B : public A
{
public:
int i;
};
Suppose that I created an object for class B
B b;
Is it possible to access A::i using b?
|
Is it possible to access A::i using b?
Yes!
How about b.A::i? ;)
|
3,872,260 | 3,872,345 | Undefined parameters in function | #include <iostream>
using namespace std;
class Imp
{
public:
int X(int) {return 50;}
int Y(int y) {return y;}
};
int main()
{
Imp i;
cout << i.X(100) << endl;
return 0;
}
This code works and prints out 50. My question is what happens to the argument passed? Just out of curiosity. :)... | The arguments for such parameters are passed in the usual way, but it is not possible to acess such parameters by name in the corresponding function definition (unusual machine architecture specific code can be written however to access the argument)
A good example is the postfix operator++ (and --) as well which is us... |
3,872,290 | 4,500,419 | How to locate a free/delete mismatch reported by Valgrind in a multithreaded program? | Here is the Valgring report:
==14546== Thread 5:
==14546== Invalid free() / delete / delete[]
==14546== at 0x490555D: free (vg_replace_malloc.c:235)
==14546== by 0x3BF7EFAA8F: free_mem (in /lib64/tls/libc-2.3.4.so)
==14546== by 0x3BF7EFA581: __libc_freeres (in /lib64/tls/libc-2.3.4.so)
==14546== by 0x480267... | I finally found the explanation for this: my unit-test executable was linked to a [third party] library it didn't use. I re-linked it without that library and the problem went away.
Also the error was detected in __libc_freeres(), a function of the gnu libc that free resources at the end of the execution. The problem m... |
3,872,342 | 3,897,320 | Command Line C++ Program to Send an EMail | I'm using VS2008 & C++ and I'm trying to create a command line program that sends an email.
I've looked on line and found some sample programs but none will compile for me.
Does anyone have an example program for me?
Thanks
| This code compiles & runs for me - after figuring out the right headers etc. Still needs command line handling, and the use of the MAPI libraries is deprecated, but what do you want for free? Original code from codeproject.com
#include "windows.h"
#include "tchar.h"
#include "mapi.h"
#include "assert.h"
#define ASSERT... |
3,872,354 | 3,873,276 | How to apply DOP and keep a nice user interface? | Currently I want to optimize my 3d engine for consoles a bit. More precisely I want to be more cache friendly and align my structures more data oriented, but also want to keep my nice user interface.
For example:
bool Init()
{
// Create a node
ISceneNode* pNode = GetSystem()->GetSceneManager()->AddNode("viewerNode"... | You will need to use smarter handles than raw pointers. There is no way around it with DOP.
This means:
class SceneNode
{
public:
std::string const& getName() const { mManager->getSceneName(mId); }
void setName(std::string const& name) { mManager->setSceneName(mId, name); }
// similar with other data
private:
... |
3,872,521 | 3,872,592 | How can moved objects be used? | After moving an object, it must be destructable:
T obj;
func(std::move(obj));
// don't use obj and let it be destroyed as normal
But what else can be done with obj? Could you move another object into it?
T obj;
func(std::move(obj));
obj = std::move(other);
Does this depend on the exact type? (E.g. std::vector could... | Yes, you can move another object into it. std::swap does this.
|
3,872,772 | 3,872,870 | Initialization of const variables | I have code like this:
bool doSomething()
{
std::cout << "I'm here!"
return true;
}
const bool x = doSomething();
If placed in a cpp-file in my Visual C++ console application, the code is executed as expected before entering the main() method.
However, if I place this code in a .cpp-file inside a static link libr... | This should set things straight.
$3.6.2/4- "It is
implementation-defined whether the
dynamic initialization of a non-local
variable with static storage duration
is done before the first statement of
main. If the initialization is
deferred to some point in time after
the first statement of main, it shall
... |
3,872,793 | 3,872,858 | C#: How do i convert a const override from C++ to C# | The line of code i need to translate from C++ to C#:
void GetAnalysisModeName( ON_wString& name ) const;
I've tried with:
public override void GetAnalysisModeName(string name){}
But it tells me that the return type has to be a string.
| A straight conversion would be:
public void GetAnalysisModeName(ref string name)
{
}
But it looks like you're also trying to override something inside of the C# class.
Judging by the message that the return type must be a string, I'd say that the signature of the method you are overriding and the signature of the C++... |
3,872,935 | 3,873,065 | Launching another project from visual studio | This must be simple, but I guess I'm searching with the wrong key words.
I have a visual studio solution(2008) that includes two projects (win32). is it possible for one to launch another? they are entirely self sufficient programs.
| Right click on Project. Select Properties. Expand Build Events, select Pre-Build Events. In Command Line put the path to your executable. Use the macro's for this.
If you need one to start before the other then set it to be a dependent of the other. Right click the Solution, select Project Dependencies and choose whi... |
3,873,241 | 3,873,277 | C++ management of strings allocated by a literal | Do I need to take care of memory allocation, scope and deletion of C++ strings allocated by a literal?
For example:
#include <string>
const char* func1() {
const char* s = "this is a literal string";
return s;
}
string func2() {
std::string s = "this is a literal string";
return s;
}
const char* func... |
func1() returns a pointer to a string literal. You must not delete string literals.
func2() (presumably, you omitted the std:: prefix) returns a std::string. It takes care of itself.
func3() returns a pointer to a string that's managed by a std::string object that's destroyed when the function exits. You must not... |
3,873,298 | 3,873,990 | first n digits of an exponentiation | How do i determine the first n digits of an exponentiation (ab).
eg: for a = 12, b = 13 & n = 4, the first 4 digits are 1069.
| Calculate ab by the following iterations:
a1 = a1,
a2 = a2,
...
ai = ai,
...
ab = ab
You have ai+1 = ai×a. Calcluate each ai not exactly. The thing is that the relative error of ab is less than n times relative error of a.
You want to get final relative error less than 10-n. Thus relative error on each step may be . R... |
3,873,445 | 3,873,615 | Are System.out, stdout and cout the exact same thing? | Are System.out, stdout and cout the EXACT same thing in Java, C and C++ respectively?
Why have three different names for the same thing (especially when C, C++ and Java have much in common)?
Also, I know what they are used for but what are they exactly, under the hood, I mean?
| cout is essentially the same as stdout but the difference is that cout is of type ostream (which essentially means that you can enter formatted data using << or unformatted data with the write method.
stdout is attached to a file descriptor (stdout is a FILE*). stdout file descriptor is 1. Because it returns a referenc... |
3,873,625 | 3,879,202 | I need C++ array class template, which is fixed-size, stack-based and doesn't require default constructor | So, I've been looking at boost::array but it does require default constructor defined.
I think the best way of filling this array with data, would be through a push_back(const T&) method. Calling it more times than SIZE (known at compile-time) would result in assert or exception, depending on build configuration. This ... | Well, I would have thought that someone would have brought the answer now, however it seems not, so let's go.
What you are wishing for is something I have myself dreamed of: a boost::optional_array<T,N>.
There are two variants:
First: similar to boost::array< boost::optional<T>, N >, that is each element may or may no... |
3,873,750 | 3,874,017 | boost unique_ptr Deletor | If I want to create a unique_ptr of type QueueList (some self defined object), how do I define a deletor for it or is there already a template 'Deletor' I can use?
I want a unique_ptr so I can safely transfer the object between threads, without sharing it between the threads.
EDIT
boost::interprocess::unique_ptr<QueueL... | Here is a simple deleter class that just calls delete on any given object:
template<typename T> struct Deleter {
void operator()(T *p)
{
delete p;
}
};
You can then use it with unique_ptr like this:
boost::interprocess::unique_ptr<QueueList, Deleter<QueueList> > LIST;
|
3,873,802 | 3,873,865 | What are Containers/Adapters? C++ | What are containers/adapters? I have basic knowledge of C++ and its sub-topics like (class/templates/STL).
Can anyone please explain in layman's language and give me a practical example of the application of containers/adapters?
| <joke>C++ is technical and hard to understand :-D</joke>
Containers are data types from STL that can contain data.
Example: vector as a dynamic array
Adapters are data types from STL that adapt a container to provide specific interface.
Example: stack providing stack interface on top of the chosen container
(side note:... |
3,874,059 | 3,893,195 | NetBeans fails to execute a Perl script when compiling C++ project | I installed NetBeans 6.9.1 with C++ support. I also installed MinGW.
When I create a C++ project and run it, I get this:
I checked the C++ configuration in NetBeans (looks good):
Perl is installed on my PC under C:\perl.
I tried reinstalling NetBeans, and I tried removing NetBeans and Perl and then reinstalled NetBe... | Apparently I had to change the path to msys in NetBeans, because I installed some package to develop in Symbian.
|
3,874,329 | 3,874,401 | Detecting the use of HRESULTs as bools | We have a big body of code that was refactored so that stuff which was plain-old C++ is now COM.
I've been spending the last couple of days hunting out places in which we missed the fact that a function that previously returned a bool now returns an HRESULT (the problem is compound by the fact that S_OK == false).
Is t... | Are you using Code Analysis for C++?
If so, you should see
C6214 per http://msdn.microsoft.com/en-us/library/yy6dx731.aspx
or
C6217 per http://msdn.microsoft.com/en-us/library/z5aa1ca1.aspx
Also verify your source code (via #pragma) and project options do not disable these or other important warnings.
|
3,874,389 | 3,874,530 | How do I get LWP using Linux glibc? | I developed a process with some threads on a Linux machine (Ubuntu). I'd like to know how can i get LWP from each thread (using a glibc function), once the PID and PPID are always the same for all the threads of the process.
UID PID PPID LWP C NLWP STIME TTY TIME CMD
root 2588 2587 2588 0 ... | Use gettid() from man page:
DESCRIPTION
gettid() returns the caller's thread ID (TID). In a single-threaded
process, the thread ID is equal to the process ID (PID, as returned by
getpid(2)). In a multithreaded process, all threads have the same PID,
but each one has a unique TID. For fur... |
3,874,488 | 3,874,509 | Passing an object to a function taking pointer as parameter | How does it work when I only have an object but my function takes a pointer to that type of object.
Someoclass test1;
SomeFunction( Someclass*)
{
//does something
};
| You pass the address of the object.
SomeFunction(&test1);
|
3,874,586 | 3,874,657 | Some questions about floating points | I'm wondering if a number is represented one way in a floating point representation, is it going to be represented in the same way in a representation that has a larger size.
That is, if a number has a particular representation as a float, will it have the same representation if that float is cast to a double and then ... | If by "same representation" you mean "exactly the same binary representation in memory except for padding", then no. Double-precision has more bits of both exponent and mantissa, and also has a different exponent bias. But I believe that any single-precision value is exactly representable in double-precision (except ... |
3,874,624 | 3,874,715 | Why doesn't std::queue support a clear() function? | I have requirement: for a function, I get the input as a stream of numbers. I mean, the function keeps on getting called with single number in each call. I am using std::queue for storing the stream of numbers. I need to process a collected set of numbers only when some condition is satisfied. If the condition is not s... | According to http://www.cplusplus.com/reference/stl/queue/,
queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access it elements.
which means that the queue uses an... |
3,874,861 | 3,875,133 | Is this usage of unordered map efficient/right way? | I want to learn about mapping functions in c/c++ in general so this is a basic program on unordered mapping. I use unordered mapping because my input data are not sorted and I read that unordered_map is very efficient. Here I've an array with which I'm creating the hash table and use the lookup function to find if the ... | You're starting off on the wrong foot. A map (ordered or otherwise) is intended to store a key along with some associated data. In your case, you're only storing a number (twice, as both the key and the data). For this situation, you want a set (again, ordered or otherwise) instead of a map.
I'd also avoid at least the... |
3,875,019 | 3,879,282 | kernel function parameter as const | say I have a kernel
foo(int a, int b)
{
__shared__ int array[a];
}
it seems a has to be a constant value, I added const in front of int. It sill didn't work out,
any idea?
foo(const int a, const int b)
{
__shared__ int array[a];
}
| While you can't have a dynamically-sized array because of the constraints of the C language (as mentioned in other answers), what you can do in CUDA is something like this:
extern __shared__ float fshared[];
__global__ void testShmem( float * result, unsigned int shmemSize ) {
// use fshared - shmemSize tells you ... |
3,875,368 | 3,875,465 | Using RakNet source with Code::Blocks on Ubuntu | Hey Forum,
So i'm trying to find out how to use the source files from RakNet with Code::Blocks, in Ubuntu. All the tutorials on the internet are for windows, or use windows ".lib files". I need to find a way to get this working but I'm getting very discouraged since this is my third day in a row that has been without ... | U should install src, headers & libs
download it here http://www.raknet.net/raknet/downloads/
try in console:
unzip RakNet-3.*.zip
cd RakNet-3.*
./bootstrap
./configure
make && sudo make install
|
3,875,384 | 3,875,886 | Assertion failure before program even starts | What is going on?! I fixed some structs, extensive amount of search/replace in my code. Then i finish and everything compiles fine, but the program crashes immediately.
This is my main function:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
exit(1);
In all logics ... | As @sbi said, it's likely global/static objects. In my experience, this (often?) happens if a string object is in a global scope which is referenced by other global object/initialization code. Due to non-deterministic initialization order, the string can be used before it has been constructed. I'd look for those cases ... |
3,875,437 | 3,875,724 | In regards to for(), why use i++ rather than ++i? | Perhaps it doesn't matter to the compiler once it optimizes, but in C/C++, I see most people make a for loop in the form of:
for (i = 0; i < arr.length; i++)
where the incrementing is done with the post fix ++. I get the difference between the two forms. i++ returns the current value of i, but then adds 1 to i on the ... | My theory (why i++ is more fashionable) is that when people learn C (or C++) they eventually learn to code iterations like this:
while( *p++ ) {
...
}
Note that the post-fix form is important here (using the infix form would create a one-off type of bug).
When the time comes to write a for loop where ++i or i++ d... |
3,875,563 | 3,875,633 | Help with Makefile: No rule to make target | CC = g++
CFLAGS = -Wall
RM = /bin/rm -rf
BIN_DIR =
ifeq "$(DEBUG)" "1"
BIN_DIR = Debug
else
BIN_DIR = Release
endif
OBJS = \
$(BIN_DIR)/Unit.o
$(BIN_DIR)/%.o: src/%.c
@echo Building "$@"
@g++ -c "$<" -o"$@"
all: $(OBJS)
clean:
$(RM) $(BIN_DIR)
.PHONY: all clean
However, when I try to build my projec... | The problem is here:
$(BIN_DIR)/%.o: src/%.c
@echo Building "$@"
@g++ -c "@<" -o"$@"
I think that's more like this :
$(BIN_DIR)%.o: %.c
$(CC) -o $@ -c $< $(CFLAGS)
|
3,875,594 | 3,875,752 | extracting last 2 words from a sequence of strings, space-separated | I have any sequence (or sentence) and i want to extract the last 2 strings.
For example,
sdfsdfds sdfs dfsd fgsd 3 dsfds should produce: 3 dsfds
sdfsd (dfgdg)gfdg fg 6 gg should produce: 6 gg
| You can use std::string::find_last_of function to find spaces.
int main()
{
std::string test = "sdfsdfds sdfs dfsd fgsd 3 dsfds";
size_t found1 = test.find_last_of( " " );
if ( found1 != string::npos ) {
size_t found2 = test.find_last_of( " ", found1-1 );
if ( found2 != string::npos )
... |
3,875,780 | 3,876,056 | Filtering out invalid user inputs | I'm trying to filter out invalid user inputs in a small C++ program using the following chunk of code:
int selection = -1;
while (!(selection >= 1 && selection <=4))
{
cin >> selection;
if (!(selection >= 1 && selection <=4))
{
cout << "invalid selection!" << endl;
... | You need to detect unconvertible input using fail() and then ignore the rest of the bad data and reset cin error flags using clear() before reading in a new input attempt.
int selection = -1;
while (!(selection >= 1 && selection <=4))
{
cin >> selection;
if (cin.fail() || !(selection >= 1 && selection <=4))... |
3,875,785 | 3,875,861 | How to delete a pointer to a pointer? | In C++, if you pass a pointer to a pointer into a method, do you delete the referenced pointer first? Do you have to clean it up within the method? I'm checking memory in task manager and it is leaking!
Thanks!!
| You delete a pointer to a pointer like this:
int** p = 0;
p = new int*; // create first pointee
*p = new int; // create 2nd pointee
**p = 0; // assign 2nd pointee
// free everything
delete *p;
delete p;
It seems unusual to me to delete a pointer that was passed into a method. But anyways:
void freeme(int... |
3,876,117 | 3,876,159 | Forward declaration issues | Here is my issue.
I have 2 classes which I want to implement in 1 h file
lets call them class Foo and class Bar. My issue is that Bar has functions which have a return value of Foo and Foo has functions with a return value of Bar.
Therefore, how do I properly forward declare these so they can play nice with each other.... | class Foo;
class Bar{
public:
Foo * getMyFoo();
private:
Foo * mMyFoo;
};
class Foo{
public:
void setMyBar(Bar *);
private:
Bar * mTheBar;
};
|
3,876,190 | 3,876,207 | Problem with running c program on mac? | I'm a total beginner in C programming so please bear with me. I have just started today and wanted to write a short program - well at least a small script that would just print out a line of text. Now here's what I did in order to achieve this:
I downloaded vim text editor and wrote this few lines of code:
#include <st... | Bash can't find your command because the current directory is not usually in the path.
Try:
$ ./a.out
|
3,876,198 | 3,876,495 | Testing with Visual Studio Test 2010 | Does any one know if I can test native code in VS Test 2010?
| Apparently not according to the docs here.
You cannot have test projects with
unit tests that use unmanaged C++.
This is confirmed by MSFT here.
|
3,876,391 | 3,876,584 | Is it possible to use System C data types in C++ without the entire System C kernel? | System C provides arbitrary length integer types that can be manipulated either as numbers (i.e. with support for artihmetic) or as bit-vectors (i.e. with support for logic operations and working with sub-vectors).
System C also provides support for all sorts of other things I don't want, such as clocks, flip flops and... | I'm not familiar with SystemC, but I do always like to point out that in open source projects, you can get the answer from the horse's mouth.
Browsing the CPP files which implement the integer type, it seems to depend on things in datatypes/, utils/, and kernel/:
http://github.com/systemc/systemc-2.2.0/tree/master/src/... |
3,876,507 | 3,991,890 | Programmatically add port forwarding entry into router using upnp? | Does someone have a simple example on how to add a port forwarding entry with upnp into the router using c++?
| There is some code that does this here. Although the title references Visual Basic, the included code is in C++.
|
3,876,544 | 3,876,567 | Adding includes causes compilation error | Compiling with Visual Studio 2005, on Windows XP. I add the following headers to my "stdafx.h" file like so:
#include <atlbase.h>
#include <atlcom.h>
#include <atlcore.h>
#include <atlstr.h>
(technically the same error appears with just atlbase.h included) which produces the following errors:
error C2334: unexpected ... | Run it through the preprocessor and see what you get. Maybe near is defined to something, or somesuch problem. (Hard to say without line numbers)
(I believe /E or /EP is the correct switches, but you can find it in the VS GUI options for a single file too..)
|
3,876,737 | 3,877,029 | C++ unit testing with VS test professional | Does any one know if I can test native code in VS Test 2010?
| As of VS2010, native C++ unit testing is not directly supported by Visual Studio. See MSDN, specifically:
You cannot have test projects with unit tests that use unmanaged C++.
You can still do native C++ unit testing with Visual Studio, but it won't be as integrated as other VS features. See this SO answer for a nu... |
3,876,758 | 3,876,880 | Working around the char array on stack align problem | See: Placement new issue
Simple question, would this solve the align problem?
union
{
char real_array[sizeof(T)*size];
T fake_array[size];
};
| Yes, that should solve the alignment problem. There's no need to make fake_array an array though. Just a single member of type T is enough.
This is actually a rather widely used trick for forcing specific alignment on some array.
As a pedantic side-note: anonymous unions only exist in C++, but not in C.
|
3,876,835 | 3,876,860 | Casting to base class validity | Say I have a class named Base and a class that derives from it called SuperBase. Given that add takes in a Base*, would either of these be valid:
SuperBase *super = new SuperBase;
bases.add(super);
Or
SuperBase *super = new SuperBase;
bases.add((Base*)super);
| The first works as long as SuperBase publicly derives from Base, via an implicit conversion from derived-to-base:
struct base { virtual ~base() {} };
struct derived : base {};
base* b = new derived; // okay
The second works as well, but ignores the protection of Base:
struct derived : private base {}; // private base... |
3,876,899 | 3,876,944 | C++ object without subclasses? | I was wondering if there is a way to declare an object in c++ to prevent it from being subclassed. Is there an equivalent to declaring a final object in Java?
| From C++ FAQ, section on inheritance
This is known as making the class
"final" or "a leaf." There are three
ways to do it: an easy technical
approach, an even easier non-technical
approach, and a slightly trickier
technical approach.
The (easy) technical approach is to
make the class's constructors private... |
3,876,921 | 3,877,127 | Metaclass to parametrize Inheritance | I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Sinc... | Although it certainly can be done with metaclasses, you can do what you want without them because in Python classes are themselves objects. The means that—surprisingly—essentially nothing more than an almost one-to-one translation of the C++ code is required. Besides being relatively uncomplicated because of this, it'l... |
3,876,966 | 4,085,217 | What does wxWidgets' EVT_CHAR_HOOK do? | I am maintaining a wxWidgets C++ application that uses EVT_CHAR_HOOK to capture key events in a high level window. I can't find any real documentation for this event but I can surmise that it intercepts key events in some way that has priority over the "standard" key events. One disturbing thing that I just discovere... | I just looked into src/gtk/window.cpp and found this piece:
// Implement OnCharHook by checking ancestor top level windows
wxWindow *parent = win;
while (parent && !parent->IsTopLevel())
parent = parent->GetParent();
if (parent)
{
event.SetEventType( wxEVT... |
3,877,052 | 3,877,084 | Making size_t and wchar_t portable? | To my understanding the representation of size_t and wchar_t are completely platform/compiler specific. For instance I have read that wchar_t on Linux is now usually 32bit, but on Windows it is 16bit. Is there any way that I can standardize these to a set size (int, long, etc.) in my own code, while still maintaining b... | You don't want to redefine those types. Instead, you can use typedefs like int32_t or int16_t (signed 32-bit and 16-bit), which are part of <stdint.h> in the C standard library.
If you're using C++, C++0x will add char16_t and char32_t, which are new types (not just typedefs for integral types) intended for UTF-16 and... |
3,877,129 | 3,877,194 | static library works in console but not in GUI app - strange | I have a strange error that has bothered me all day. I have a library function that I have compiled. I statically link the library to test it in a separate console application and everything builds and works ok. It is just a simple sqrt function called sqrtval at the moment. However, when I include this library in a la... | If your library is written in plain C, you have to declare sqrtval as:
extern "C" double sqrtval(double);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.