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,060,295 | 3,060,327 | "Socket operation on non-socket" error due to strange syntax | I ran across the error Socket operation on non-socket in some of my networking code when calling connect and spent a lot of time trying to figure out what was causing it. I finally figured out that the following line of code was causing the problem:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol) < 0)) {
See the problem? Here's what the line should look like:
if ((sockfd = socket( ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {
What I don't understand is why the first, incorrect line doesn't produce a warning. To put it another way, shouldn't the general form:
if ( foo = bar() < baz ) do_something();
look odd to the compiler, especially running with g++ -Wall -Wextra?
If not, shouldn't it at least show up as "bad style" to cppcheck, which I'm also running as part of my compile?
| Actually, you don't get any warning because of the double parenthesis (.
Try to remove one pair, and you'll get the warning back.
#include <iostream>
int foo()
{
return 2;
}
int main(int /*argc*/, char** /*argv*/)
{
int l;
if ((l = foo() < 3)) // Won't generate warning under gcc
{
}
if (l = foo() < 3) // will generate a warning "warning: suggest parentheses around assignment used as truth value"
{
}
return EXIT_SUCCESS;
}
To avoid such annoying mistakes/typos, I avoid assigning a value and testing it in the same statement. That's too much error prone imho.
|
3,060,348 | 3,060,907 | what are the devices will be listed | please let me know what are the devices wil be listed using the below code
guid = GUID_DEVINTERFACE_VOLUME;
// Get device Information handle for Volume interface
hDevInfo = SetupDiGetClassDevs( &guid, NULL, NULL,
DIGCF_DEVICEINTERFACE | DIGCF_PRESENT );
Thank you
| All devices that are present in the system that have enabled an interface from the storage volume device interface class.
You can find more information here
|
3,060,417 | 3,060,462 | Compile C++ program on Mac to run on Linux |
Possible Duplicate:
How to cross compile from Mac OS X to Linux x86?
I have an application that I wrote in C++/SDL, using FMOD library. The app is portable and compiles without any code change on Mac and on Linux. But one annoyance is that when I want to ship Linux version, I have to run my Linux box, copy the source code over there (over USB drive, because I have no network there, it's an old laptop) and compile it, then copy it again over USB to my Mac and upload it.
My question is - is there a better way of doing it? Ideally, could I compile the app to run on Linux directly from Xcode, where I compile it for Mac?
| A quick google for cross-compiling for Linux on OSX revealed this page.
Actually, this has been asked before in How to cross compile from Mac OS X to Linux x86?.
|
3,060,440 | 3,060,594 | Avoid Resource Conflict | I have a MFC exe, trying to dynamic load a MFC dll.
// This is code in MFC exe
HINSTANCE h = AfxLoadLibrary(_T("DLL.dll"));
typedef void(*FUN)();
FUN fun = (FUN)GetProcAddress(h, "loveme");
FreeLibrary(h);
Both MFC exe and MFC dll, are having their own resource file.
However, I realize that, if MFC exe and MFC dll are having a same resource ID, conflict may occur.
// This is code in MFC dll. Both exe and dll, are having resources with
// ID 101.
CString s;
s.LoadString(101);
// Resource 101 in exe is being shown :(
AfxMessageBox(s);
May I know how I can avoid resource ID conflict problem? Can we have two resource in both MFC and DLL, although their ID is different, but they are independent from each other?
This means, DLL will only load DLL's resource. EXE will only load EXE's resource.
| You will need to keep track handle to yourself, which will be passed in during dllmain.
HINSTANCE hDLLInstance = 0;
extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
hDLLInstance = hInstance;
...
}
then when you want to refer to local resources (ie. LoadString), pass the dll handle
...
CString s;
s.LoadString(hDLLInstance, 101);
AfxMessageBox(s);
...
|
3,060,545 | 3,060,625 | can function return 0 as reference | I have this snippet of the code
Account& Company::findAccount(int id){
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
if(i->nID == id){
return *i;
}
}
return 0;
}
Is this right way to return 0 if I didn't find appropriate account?
cause I receive an error:
no match for 'operator!' in '!((Company*)this)->Company::findAccount(id)'
I use it this way:
if(!(findAccount(id))){
throw "hey";
}
thanks in advance
| Why don't you use a standard algorithm like std::find_if.
Edit: Explanation of find_if.
Here is the reference for find_if algorithm. http://cplusplus.com/reference/algorithm/find_if/
bool isEqual(int id1, int id2) {
return id1 == id2;
}
void foo() {
std::list<Account> accountList;
// Fill this list here.
list<Account>::iterator it = std::find_if(accountList.begin(), accountList.end(), bind(isEqual, idYouSearch, _1));
Account ac = *it;
}
You might need additional includes for bind and _1 placeholder. Propably there is a std Predicate for isEqual and you could use this instead.
|
3,060,572 | 3,060,885 | c++ protected pointer member to the same class and access privileges | Example code is included at the bottom of the message.
I'm puzzled about the protected access specifier in a class.
I have define a class node which has a protected string member name
string name;
and a vector of node pointers
vector args;
Before I thought that a member function of node could not do
args[0]->name
but a program that does just this does compile and run.
However, now I would like to inherit this class and access the name field
in one of the args array pointers from this derived class
args[0]->name
but this does not compile. When I compile the example code below with
the commented sections uncommented, the compiler reports:
Compiler output:
g++ test.cc -o test
test.cc: In member function 'void foo::newnode::print_args2()':
test.cc:22: error: 'std::string foo::node::name' is protected
test.cc:61: error: within this context
Compilation exited abnormally with code 1 at Thu Jun 17 12:40:12
Questions:
Why can I access the name field of the node pointers in args in
class node, because this is what I would excpect from a similarly
defined private field in Java.
How can I access those fields from the derived class.
Example code:
#include <iostream>
#include <vector>
using namespace std;
namespace foo
{
class node;
typedef std::vector<node*> nodes;
class node
{
public:
node (string _name);
void print_args ();
void add_node (node* a);
protected:
nodes args;
string name;
};
}
foo::node::node (string _name)
: args(0)
{
name = _name;
}
void foo::node::add_node (node* a)
{
args.push_back(a);
}
void foo::node::print_args ()
{
for (int i = 0; i < args.size(); i++)
{
cout << "node " << i << ": " << args[i]->name << endl;
}
}
// namespace foo
// {
// class newnode : public node
// {
// public:
// newnode (string _name) : node(_name) {}
// void print_args2 ();
// protected:
// };
// }
// void foo::newnode::print_args2 ()
// {
// for (int i = 0; i < args.size(); i++)
// {
// cout << "node " << i << ": " << args[i]->name << endl;
// }
// }
int main (int argc, char** argv)
{
foo::node a ("a");
foo::node b ("b");
foo::node c ("c");
a.add_node (&b);
a.add_node (&c);
a.print_args ();
// foo::newnode newa ("newa");
// foo::newnode newb ("newb");
// foo::newnode newc ("newc");
// newa.add_node (&newb);
// newa.add_node (&newc);
// newa.print_args2 ();
return 0;
}
| The compiler will allow that an object A accesses private/protected members of an object B if A and B have the same static type.
I will try to make this clear with an example:
class Base
{
protected:
int a;
};
class Derived : public Base
{
public:
void foo(Base& b, Derived& d)
{
//allowed because this obviously has the same type as this :)
a = 1;
//allowed because this has the same type as d (Derived)
d.a = 1;
//not allowed because this (Derived) does not have the same
//type as b (Base). They might have the same dynamic type
//but the compiler has no way of knowing this.
b.a = 1;
}
};
So, to answer your questions:
Class node is allowed to access the name field if the node pointers of your args vector because they are also of class node.
You cannot directly. You either have to make the field public (I wouldn't do that) or make public accessors.
|
3,060,577 | 3,090,854 | Can the dirtiness of pages of a mmap be found from userspace? | Can dirtiness of pages of a (non-shared) mmap be accessed from userspace under linux 2.6.30+? Platform-specific hacks and kludges welcome.
Ideally, I'm looking for an array of bits, one per page (4kB?) of the mmap'ed region, which are set if that page has been written to since the region was mmap'ed.
(I am aware, that the process doing the writing could keep track of this information - but it seems silly to do so if the kernel is doing it anyway.)
Thanks,
Chris.
| See /proc/*/pagemap and /proc/kpageflags interfaces.
First tells you PFN for an address, second tells you dirty bit given PFN.
See fs/proc/task_mmu.c , Documentation/vm/pagemap.txt, Documentation/vm/page-types.c .
|
3,060,670 | 3,062,760 | Is there any API to get path "C:\Documents and Settings" in windows? | Is there any API to get path : "C:\Documents and Settings" in windows in c++?
not: C:\Documents and Settings\brianfu\My Documents.
Many Thanks!
Thanks for luke's solution:
GetProfilesDirectory
it works!
| GetProfilesDirectory
|
3,060,671 | 3,060,692 | Does this code follow the definition of recursion? | I have a piece of code which I am doubting it as a implementation of recursion by its definition. My understanding is that the code must call itself, the exact same function. I also question whether writing the code this way adds additional overhead which can be seen with the use of recursion. What are your thoughts?
class dhObject
{
public:
dhObject** children;
int numChildren;
GLdouble linkLength; //ai
GLdouble theta; //angle of rot about the z axis
GLdouble twist; //about the x axis
GLdouble displacement; // displacement from the end point of prev along z
GLdouble thetaMax;
GLdouble thetaMin;
GLdouble thetaInc;
GLdouble direction;
dhObject(ifstream &fin)
{
fin >> numChildren >> linkLength >> theta >> twist >> displacement >> thetaMax >> thetaMin;
//std::cout << numChildren << std::endl;
direction = 1;
thetaInc = 1.0;
if (numChildren > 0)
{
children = new dhObject*[numChildren];
for(int i = 0; i < numChildren; ++i)
{
children[i] = new dhObject(fin);
}
}
}
void traverse(void)
{
glPushMatrix();
//draw move initial and draw
transform();
draw();
//draw children
for(int i = 0; i < numChildren; ++i)
{
children[i]->traverse();
}
glPopMatrix();
}
void update(void)
{
//Update the animation, if it has finished all animation go backwards
if (theta <= thetaMin)
{
thetaInc = 1.0;
} else if (theta >= thetaMax)
{
thetaInc = -1.0;
}
theta += thetaInc;
//std::cout << thetaMin << " " << theta << " " << thetaMax << std::endl;
for(int i = 0; i < numChildren; ++i)
{
children[i]->update();
}
}
void draw(void)
{
glPushMatrix();
glColor3f (0.0f,0.0f,1.0f);
glutSolidCube(0.1);
glPopMatrix();
}
void transform(void)
{
//Move in the correct way, R, T, T, R
glRotatef(theta, 0, 0, 1.0);
glTranslatef(0,0,displacement);
glTranslatef(linkLength, 0,0);
glRotatef(twist, 1.0,0.0,0.0);
}
};
| Yes, since you have certain functions calling themselves. By definition that is direct recursion. You could also have indirect recursion if you had function A() calling function B(), function B() in turn (directly or indirectly) calling function A() again.
|
3,060,688 | 3,060,701 | Prohibiting copy construction and copy assignment in C++ | To prohibit copy construction and copy assignment, I've seen the boost noncopyable class and in the Google style guide the DISALLOW_COPY_AND_ASSIGN macro. Is there any reason to prefer one of the techniques over the other, or any subtle differences one should be aware of?
| I prefer boost noncopyable over the macro because it's not a macro and it is easier (IMO) to use.
In real code, i'm using neither of them and write the two declarations needed myself.
A subtle difference you might be interested in, though, is that using that macro or your own declarations will not give a compiler error when the class itself tries to copy the object (but rather fail to link later on). noncopyable however will also signal a compiler error in this case, because it's the base-class that has the functions declared private, not the class itself.
|
3,060,730 | 3,060,745 | C++: Avoid .cpp files with only an empty (de)constructor | When I have a header file like this:
#ifndef GAMEVIEW_H_
#define GAMEVIEW_H_
#include <SDL/SDL.h>
class GameView
{
public:
GameView();
virtual ~GameView();
virtual void Update() = 0;
virtual void Render(SDL_Surface* buffer) = 0;
};
#endif /* GAMEVIEW_H_ */
I need to create a .cpp file like this:
#include "GameView.h"
GameView::~GameView()
{
}
GameView::GameView()
{
}
This is a bit stupid. Just a .cpp file for an empty constructor and deconstructor.
I want to implement that method simply in the header file. That is much cleaner.
How to do this?
| You can define your constructor and destructor (this is the proper term, use this instead of deconstructor) inline:
class GameView
{
public:
GameView() {}
virtual ~GameView() {}
virtual void Update() = 0;
virtual void Render(SDL_Surface* buffer) = 0;
};
|
3,060,776 | 3,060,818 | Compiler doesn't find methods from base class | I am having a problem with my virtual methods in a derived class. Here are my (simplified) C++ classes.
class Base
virtual method accept( MyVisitor1* v ) { /*implementation is here*/ };
virtual method accept( MyVisitor2* v ) { /*implementation is here*/ };
virtual method accept( MyVisitor3* v ) { /*implementation is here*/ };
class DerivedClass
virtual method accept( MyVisitor2* v ) { /*implementation is here*/ };
The following use causes VS 2005 to give: "error C2664: 'DerivedClass::accept' : cannot convert parameter 1 from 'Visitor1*' to 'Visitor2 *'".
DerivedClass c;
MyVisitor1 v1;
c.accept(v1);
I was expecting the compiler to find and call Base::accept(MyVisitor1) for my DerivedClass as well. Obviously this is not working, but I don't understand why. Any ideas?
Thanks,
Paul
| The accept member of DerivedClass hides any members of the base class with the same name, even if they have different signatures. To include them, add the following to the definition of DerivedClass:
using Base::accept;
(I'm assuming that DerivedClass does derive from Base; your snippet doesn't explicitly say that).
|
3,060,828 | 3,060,865 | Is the order of declarations within a class important? | Can somebody please explain the order of private and public in a class. Is it important or not?
For example:
class Account{
public:
Account(string firstName, string lastName, int id);
void printAccount();
private:
string strLastName;
string strFirstName;
};
Will it be the same as:
class Account{
private:
string strLastName;
string strFirstName;
public:
Account(string firstName, string lastName, int id);
void printAccount();
};
| It's important for the visibility of class members
class Account{
public:
Account(string firstName, string lastName, int id);
void printAccount();
Foo makeFoo(); // invalid! Foo not declared yet
typedef Foo foo_type; // invalid! Foo not declared yet
private:
string strLastName;
string strFirstName;
class Foo { };
};
You can only refer to a not yet declared name in a parameter, default argument, function body or constructor initialization list in class (or such things in nested classes). In other cases, you can't and you have to arrange declarations such that they are visible.
|
3,060,911 | 3,060,939 | An exception to the "only one implementation" rule? | While I was reading the accepted answer of this question, I had the following question:
Typically, methods are defined in header files (.hpp or whatever), and implementation in source files (.cpp or whatever).
One of the main reasons it is bad practice to ever include a "source file" (#include <source_file.cpp>) is that its methods implementation would then be duplicated, resulting in linking errors.
When one writes:
#ifndef BRITNEYSPEARS_HPP
#define BRITNEYSPEARS_HPP
class BritneySpears
{
public:
BritneySpears() {}; // Here the constructor has implementation.
};
#endif /* BRITNEYSPEARS_HPP */
He is giving the implementation of the constructor (here an "empty" implementation, but still).
But why then including this header file multiple times (aka. on different source files) will not generate a "duplicate definition" error at link time ?
| Inline functions are exceptions to the "one definition rule": you are allowed to have identical implementations of them in more than one compilation unit. Functions are inline if they are declared inline or implemented inside a class definition.
|
3,060,946 | 3,060,998 | Implementing a State Machine in C++ HOW? | I'm new to C++.
How can I implement a State Machine in C++ ?
I'm getting only the messages and should know the next state.
What is the proper structure I need to use ?
Thanks, Igal
| typedef std::pair<State,Message> StateMessagePair;
typedef std::map<StateMessagePair,State> StateDiagram;
StateDiagram sd;
// add logic to diagram
...
State currentState = getInitialState();
...
// process message
Message m = getMessage();
StateDiagram::iterator it=sd.find(std::make_pair(currentState,m)));
if (it==sd.end()) exit("incorrect message");
currentState = it->second;
EDIT:
Building up the state diagram is done like this (example is for a cola-vending machine):
StateDiagram.insert(std::make_pair(State::Idle ,Message::MakeChoice ),State::WaitingForMoney);
StateDiagram.insert(std::make_pair(State::WaitingForMoney,Message::Cancel ),State::Idle);
StateDiagram.insert(std::make_pair(State::WaitingForMoney,Message::MoneyEntered ),State::FindCan);
StateDiagram.insert(std::make_pair(State::FindCan ,Message::CanSentToUser),State::Idle);
Default actions can be implemented using a second map, where the key is only the State, like this:
typedef std::map<State,State> StateDiagramForDefaults;
Instead of printing "incorrect message", the logic can perform a lookup in the StateDiagramForDefaults.
If actions needs to be added to the state diagram, the value of the map should be a pair consisting of an action, and a new state, like this:
typedef std::pair<State,Message> StateMessagePair;
typedef std::pair<State,IAction *> StateActionPair;
typedef std::map<StateMessagePair,StateActionPair> StateDiagram;
The logic that builds up the diagram should then "new" an instance of a class that implements IAction, and put that in the StateDiagram.
The executing logic then just executes the IAction implementation via a virtual method (e.g. execute() or the ()-operator).
|
3,061,135 | 3,061,170 | Can we write an EOF character ourselves? | Most of the languages like C++ when writing into a file, put an EOF character even if we miss to write statements like :
filestream.close
However is there any way, we can put the EOF character according to our requirement, in C++, for an instance.
Or any other method we may use apart from using the functions provided in C++.
If you need to ask more of information then kindly do give a comment.
Thanks in advance.
EDIT: Thanks for your support but here's an addition to this question:
What if, we want to trick the OS and place an EOF character in a file and write some data after the EOF so that an application like notepad.exe is not able to read after our EOF character.
I have read answers to the question related to this topic and have come to know that nowdays OS generally don't see for an EOF character rather check the length of file to get the correct idea of knowing about the length of the file but, there must be a procedure in OS which would be checking the length of file and then updating the file records.
I am sorry if I am wrong at any point in my estimation but please do help me coz it can lead to a lot of new ideas.
| There is no EOF character. EOF by definition "is unequal to any valid character code". Often it is -1. It is not written into the file at any point.
There is a historical EOF character value (CTRL+Z) in DOS, but it is obsolete these days.
To answer the follow-up question of Apoorv: The OS never uses the file data to determine file length (files are not 'null terminated' in any way). So you cannot trick the OS. Perhaps old, stupid programs won't read after CTRL+Z character. I wouldn't assume that any Windows application (even Notepad) would do that. My guess is that it would be easier to trick them with a null (\0) character.
|
3,061,203 | 3,061,272 | Implicit conversion while using += operator? | Conside the following code:
int main()
{
signed char a = 10;
a += a; // Line 5
a = a + a;
return 0;
}
I am getting this warning at Line 5:
d:\codes\operator cast\operator
cast\test.cpp(5) : warning C4244: '+='
: conversion from 'int' to 'signed
char', possible loss of data
Does this mean that += operator makes an implicit cast of the right hand operator to int?
P.S: I am using Visual studio 2005
Edit: This issue occurs only when the warning level is set to 4
| What you are seeing is the result of integral promotion.
Integral promotion is applied to both arguments to most binary expressions involving integer types. This means that anything of integer type that is narrower than an int is promoted to an int (or possibly unsigned int) before the operation is performed.
This means that a += a is performed as an int calculation but because the result is stored back into a which is a char the result has to undergo a narrowing conversion, hence the warning.
|
3,061,247 | 3,061,350 | Initialization of a vector of vectors? | Is there a way to initialize a vector of vectors in the same ,quick, manner as you initialize a matrix?
typedef int type;
type matrix[2][2]=
{
{1,0},{0,1}
};
vector<vector<type> > vectorMatrix; //???
| For the single vector you can use following:
typedef int type;
type elements[] = {0,1,2,3,4,5,6,7,8,9};
vector<int> vec(elements, elements + sizeof(elements) / sizeof(type) );
Based on that you could use following:
type matrix[2][2]=
{
{1,0},{0,1}
};
vector<int> row_0_vec(matrix[0], matrix[0] + sizeof(matrix[0]) / sizeof(type) );
vector<int> row_1_vec(matrix[1], matrix[1] + sizeof(matrix[1]) / sizeof(type) );
vector<vector<type> > vectorMatrix;
vectorMatrix.push_back(row_0_vec);
vectorMatrix.push_back(row_1_vec);
In c++0x, you be able to initialize standard containers in a same way as arrays.
|
3,061,324 | 3,061,437 | returning of the iterator in C++ | can somebody explain I can I return list iterator?
list<Account>::iterator Company::findAccount(int id){
for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
if(i->getID() == id){
return i;
}
}
return 0;
}
and also is it good practice, to return list iterator?
edited
also can use this function in the statesments:
if(findAccount(id)){
throw "hey";
return;
}
| In your case returning an iterator exposes internals of the class, and that is almost always a bad thing. As @Paul said in his answer, some STL-algorithms return iterators. However, they return iterators on the input-collection.
From the name of your method I guess it would be the best thing to return an object or a const reference.
About your edit, you may want to look into the Null Object Pattern. Alternatively you can provide a method DoesAccountExist. If a call to that method returns true, a call to findAccount must succeed, otherwise it can throw an exception.
|
3,061,341 | 3,061,494 | error in c, but not in c++ | const int t=5;
char buf[t+5];
When I compile this gives error in C but not in C++!!
Can anybody please explain me the reason?
Note: I know the const defaults to internal linkage in 'C++', where as in 'C' it defaults to external linkage. Does it has any relation to the above case??
| As others explained, C is kept more simple than C++ and doesn't allow const variables to appear in integer constant expressions. But in both C89 and C++ declared arrays must have compile-time constant sizes.
You can use enumerations for this
enum {
BufSize = 5
};
char buf[BufSize + 5];
It doesn't have to do with internal linkage - external linkage variables are equally viable in integer constant expressions in C++. The internal linkage in C++ rather is a consequence, but not a neccessity, of allowing them to appear in constant expressions. The C++ Standard explains why they have internal linkage by default
Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units
|
3,061,528 | 3,066,996 | Is there a way to have multiple "name=value" lines in the INI file using boost::program_options::parse_config_file? | I want to be able to specify multiple name=value lines in the INI file using boost::program_options. Something like
[list.names]
name=value
name=value2
name=value3
Is there a way to achieve this with boost::program_options? I get a multiple occurrences error if I try it
If not, what other libraries are available?
| Specify the value of the field as std::vector<value_type> in the options_description:
namespace po = boost::program_options;
po::options_description desc;
desc.add_options()
("list.names.name", po::value< std::vector<std::string> >(), "A collection of string values");
po::variables_map vm;
std::ifstream ini_file("config.ini");
po::store(po::parse_config_file(ini_file, desc), vm);
po::notify(variables);
if (vm.count("list.names.name"))
{
const std::vector<std::string>& values = vm["list.names.name"].as< std::vector<std::string> >();
std::copy(values.begin(), values.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
|
3,061,582 | 3,061,610 | Include all files in a directory? | How can one achieve what the following code is trying to do?
#include "dir/*"
| In Bash:
HEADER=all_headers.h
echo "#ifndef __ALL_HEADERS__" > $HEADER
echo "#define __ALL_HEADERS__" >> $HEADER
for file in dir/*.h
do
echo "#include <$file>" >> $HEADER
done
echo "#endif" >> $HEADER
|
3,061,698 | 3,061,717 | auto_inline - inadequate documentation | I want to disable inlining for a particular function. What the compiler does for everything else should be as specified in the project properties. I found a page on a forum which suggested the following:
#pragma auto_inline(off)
void func()
{
}
#pragma auto_inline()
The author suggested that calling auto_inline() with no arguments will set the compiler to revert to doing whatever the default action was before the call to auto_inline(off). Can anyone confirm that this works for visual studio 2008? I ask because the VS2008 documentation makes no mention at all of what happens if you call this function with no arguments.
| __declspec(noinline) void func()
{
}
|
3,061,721 | 3,062,065 | Concatenate boost::dynamic_bitset or std::bitset | what is the best way to concatenate 2 bitsets?
For example i've got
boost::dynamic_bitset<> test1( std::string("1111") );
boost::dynamic_bitset<> test2( std::string("00") );
they should be concatenated into a thrid Bitset test3 which then holds
111100
Solutions should use boost::dynamic_bitset. If the solution works with std::bitset, it would be nice too. There should be a focus on performance when concatenating the bits.
UPDATE:
I've compared both methods (stringmethod from me and Neil and shiftmethod from messenger) and the stringmethod was a lot faster (factor 10++). Code here:
http://pastebin.com/HfpfYfy8
I hope Pastebin is ok for posting long code-listings. If there is a better way please contact me.
| For the standard bitset, something like:
#include <bitset>
#include <string>
#include <iostream>
using namespace std;
template <size_t N1, size_t N2 >
bitset <N1 + N2> concat( const bitset <N1> & b1, const bitset <N2> & b2 ) {
string s1 = b1.to_string();
string s2 = b2.to_string();
return bitset <N1 + N2>( s1 + s2 );
}
int main() {
bitset <4> a( string("1010") );
bitset <2> b( string("11") );
cout << concat( a, b ) << endl;
}
|
3,061,821 | 3,061,882 | c++ polymorphism and other function question | i have got this code:
class father{
public:
virtual void f() { cout<<1;}
};
class son:public father{
public:
void f() {cout<<2;}
};
void test (father x){x.f();}
int main(){
son s;
test(s);
}
the question says:
the output is '1', what is the rule about polymorphism that the programmer forgot and how can i fix it so the output would be '2'?
there is another rule that the programmer forgot when he wrote the father class, and he need to add an empty function to avoid problems from other sons of the father class. what is the rule and what is the missing function?
another question
write the g function so the next code would run with no crashes
int x=11; g(x)=22;
| When you pass the son object to the test function by value, it will be converted to a father object because test takes a father, not a son. If you want to accept instances of subclass without conversion, you need to accept the argument by reference or pointer.
So if you change the signature of test to void test (father& x), it will work as you want.
|
3,061,910 | 3,061,919 | How to clean up a vector/map properly? | If I have a vector<string*> *vect or a map<pair<string*, int*>, string*> *map,
how to clean up everything (including all object the vector/map contains)?
(Everything (vector, map, contents, string, ints) is allocated with new)
Is this enough:
delete vect;
delete map;
| No, you must iterate through the vector/ map, remove and delete its items one by one (which, as @SB pointed out, may require disposing of their members recursively).
(You could get away by simply deleting the items, if you are absolutely sure no one will access the vector elements anymore before the vector gets deleted - but it is still safer to remove each item before deleting it. This ensures program correctness at any point, eliminating the possibility for subtle bugs and easing maintenance in the long term.)
By the way this is one of the reasons why it is recommended to store smart pointers in collections, instead of raw pointers.
|
3,061,979 | 3,062,002 | operator << overload c++ | how can i overload "<<" operator (for cout) so i could do "cout" to a class k
| The canonical implementation of the output operator for any type T is this:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
os << obj.get_data1() << get_data2();
return os;
}
Note that output stream operators commonly are not member functions. (That's because for binary operators to be member functions they have to be members of their left-hand argument's type. That's a stream, however, and not your own type. There is the exception of a few overloads of operator<<() for some built-ins, which are members of the output stream class.)
Therefor, if not all data of T is publicly accessible, this operator has to be a friend of T
class T {
friend std::ostream& operator<<(std::ostream&, const T&);
// ...
};
or the operator calls a public function which does the streaming:
class T {
public:
void write_to_stream(std::ostream&);
// ...
};
std::ostream& operator<<(std::ostream& os, const T& obj)
{
obj.write_to_stream(os);
return os;
}
The advantage of the latter is that the write_to_stream() member function can be virtual (and pure), allowing polymorphic classes to be streamed.
If you want to be fancy and support all kinds of streams, you'd have to templatize that:
template< typename TCh, typename TTr >
std::basic_ostream<TCh,TTr>& operator<<(std::basic_ostream<TCh,TTr>& os, const T& obj)
{
os << obj.get_data1() << get_data2();
return os;
}
(Templates, however, don't work with virtual functions.)
|
3,062,162 | 3,062,279 | how to emulate thread local storage at user space in C++? | I am working on a mobile platform over Nucleus RTOS. It uses Nucleus Threading system but it doesn't have support for explicit thread local storage i.e, TlsAlloc, TlsSetValue, TlsGetValue, TlsFree APIs. The platform doesn't have user space pthreads as well.
I found that __thread storage modifier is present in most of the C++ compilers. But i don't know how to make it work for my kind of usage. How does __thread keyword can be mapped with explicit thread local storage? I read many articles but nothing is so clear for giving me the following basic information
will __thread variable different for each thread ?
How to write to that and read from it ? does each thread has exactly one copy of the variable ?
following is the pthread based implementation:
pthread_key_t m_key;
struct Data : Noncopyable {
Data(T* value, void* owner) : value(value), owner(owner) {}
int* value;
};
inline ThreadSpecific()
{
int error = pthread_key_create(&m_key, destroy);
if (error)
CRASH();
}
inline ~ThreadSpecific()
{
pthread_key_delete(m_key); // Does not invoke destructor functions.
}
inline T* get()
{
Data* data = static_cast<Data*>(pthread_getspecific(m_key));
return data ? data->value : 0;
}
inline void set(T* ptr)
{
ASSERT(!get());
pthread_setspecific(m_key, new Data(ptr, this));
}
How to make the above code use __thread way to set & get specific value ? where/when does the create & delete happen?
If this is not possible, how to write custom pthread_setspecific, pthread_getspecific kind of APIs.
I tried using a C++ global map and index it uniquely for each thread and retrieved data from it. But it didn't work well.
| I alwasy used the ACE library when needing thread local storage. I don't know if it is available for your system. If so check out class ACE_TSS.
For the __thread keyword, there is an wikipedia page, where it is described.
|
3,062,258 | 3,062,316 | vector holding read-only matrices? | I want to use a vector to hold read-only integer-matrices of the size 5x5
vector<const int[5][5]> startingPieces;
But this declaration causes a bunch of weird errors I've never ever seen before.
error C2535: 'const int (*std::allocator<_Ty>::address(const int (&)[5][5]) const)[5][5]' : member function already defined or declared
1> with
1> [
1> _Ty=const int [5][5]
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\xmemory(109) : see declaration of 'std::allocator<_Ty>::address'
1> with
1> [
1> _Ty=const int [5][5]
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\vector(429) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1> with
1> [
1> _Ty=const int [5][5]
1> ]
1> c:\program files\microsoft visual studio 9.0\vc\include\vector(439) : see reference to class template instantiation 'std::_Vector_val<_Ty,_Alloc>' being compiled
1> with
1> [
1> _Ty=const int [5][5],
1> _Alloc=std::allocator<const int [5][5]>
1> ]
1> c:\users\eric\documents\visual studio 2008\projects\testing grounds\testing grounds\main.cpp(14) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1> with
1> [
1> _Ty=const int [5][5]
1> ]
So, what is wrong with this declaration?
| What you should do here is create your own matrix class that stores the 5x5 array of data and then create your vector with that.
|
3,062,277 | 3,062,368 | Sample Code with Examples for the C++ Google Style Guide? | Are there any good places to get examples for the C++ Google Style Guide?
| Google open sources a number of projects, most of which comply with their style guides:
protocol buffers
re2 - pcre regular expressions
perf tools - multithreaded performance analysis tools
gflags - command line flags
Search Google code for google projects, and you'll find a lot!
|
3,062,331 | 3,062,367 | C++ template restrictions | I wondering is there any way to set restrictions on template class?
Specify that every type substituted in template must have specific ancestor (realize some interface).
template < class B > //and every B must be a child of abstract C
class A {
public:
B * obj;
int f() {
return B::x + this->obj->f();
}
};
Like => in haskell
func :: (Ord a, Show b) => a -> b -> c
| You can use BOOST_STATIC_ASSERT or a similar library to assert your restrictions on the template parameter.
For example:
#include <limits>
#include <boost/static_assert.hpp>
template <class UnsignedInt>
class myclass
{
private:
BOOST_STATIC_ASSERT((std::numeric_limits<UnsignedInt>::digits >= 16)
&& std::numeric_limits<UnsignedInt>::is_specialized
&& std::numeric_limits<UnsignedInt>::is_integer
&& !std::numeric_limits<UnsignedInt>::is_signed);
public:
/* details here */
};
EDIT: For your example, you can write
template < class B >
class A {
BOOST_STATIC_ASSERT(boost::is_base_of<C, B>);
public:
B * obj;
int f() {
return B::x + this->obj->f();
}
};
|
3,062,360 | 3,062,444 | Const Member function Vs Const Friend Function | How this code modifies a value in a const function:
#include<iostream>
using namespace std;
class Y;
class X{
public:
void access(Y &y) const;
};
class Y{
int d;
public:
friend void X::access(Y &y) const;
Y(){d=0;}
};
void X::access(Y &y) const
{
cout<<"Y is "<<y.d<<endl;
y.d=1;
cout<<"Y is "<<y.d<<endl;
}
int main() {
X x;
Y y;
x.access(y);
}
And this code gives an error:
#include<iostream>
using namespace std;
class Y{
int d;
public:
void set() const{d=0;}
};
int main() {
Y y1;
return 0;
}
| Because inside a const function, only *this is const, not the parameters passed to the function or anything else.
|
3,062,518 | 3,062,822 | What kind of good approaches do C++ programmers use for storing error messages? | Say I have a huge amount of code and have different kinds of error messages. For these, I want to have a separate place where I store error codes and error messages. For example, for an error that occured because the program could not open a file I store:
F001 "Can not open a file." "The same error message in another language" "The same error message in a third language"
What is the best way to store different kinds of error messages and codes in a file for C++ programmers in order to use them quickly and easily in a programme?
FYI I am working with the Qt lib.
| I would use XML like this:
<languageList>
<language short="de" long="Deutsch" default="true" />
<language short="en" long="English" />
</languageList>
<string alias="couldNotOpenFileError"
de="Konnte Datei nicht öffnen"
en="Could not open file"
/>
<string alias="couldNotWriteFileError"
de="Konnte Datei nicht schreiben"
en="Could not write file"
/>
In code you could use it like this where you set the actual language in the message pool.
String errorMsg = ErrorMessagePool.get("couldNotOpenFileError") + additionalInformationString;
Edit: The idea of the message pool is just to wrap an existing xml parser+some additional logic.
|
3,062,616 | 3,062,736 | an error within context | can somebody please explain my mistake, I have this class:
class Account
{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
friend string printAccount(string firstName, string lastName, int id, int lines, double lastBill);
}
but when I call it:
string reportAccounts() const
{
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i)
{
report += printAccount(i->strFirstName, i->strLastName, i->nID, i->nLines, i->lastBill);;
}
return report;
}
I receive error within context, can somebody explain why?
| I imagine the full error has something to do with "These members are private within context" and some line numbers.
The issue is that i->strFirstName is private from the perspective of the reportAccounts() function. A better solution may be:
class Account{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
string print() const
{
return printAccount(this->strLastName, this->strFirstName, this->nID,
this->nLines, this->lastBill);
}
};
And then
string reportAccounts() const {
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
report += i->print();
}
return report;
}
Another option is to make printAccount take a reference to an Account (friend printAccount(const Account& account)), and it can then access the private variables through the reference.
However, the fact that the function is called print Account suggests that it might be better as a public class function.
|
3,062,647 | 3,062,899 | How to get every virtual function index just as the compiler does? | Is there some plugin or tool which can read a .h file (or simply modify Intellisense itself) and spit out every function and it's virtual function table index? There's a pattern which I have yet to figure out having to do with polymorphism, and it gets 5x harder when you start to have 5 classes or more deriving from each other. No matter what, though, the MSVC++ compiler always spits out the correct virtual function table index when it compiles the virtual function call from C++ to Assembly. There has to be a better way to get that index without loading, break-pointing, reading the offset, and rewriting the code, right?
Thanks!
| Use the hidden Microsoft C/C++ compiler option "/d1 reportAllClassLayout". This will print out the memory layout and vtables of all your classes.
|
3,062,734 | 3,063,148 | Possible to distribute an MPI (C++) program accross the internet rather than within a LAN cluster? | I've written some MPI code which works flawlessly on large clusters. Each node in the cluster has the same cpu architecture and has access to a networked (i.e. 'common') file system (so that each node can excecute the actual binary). But consider this scenario:
I have a machine in my office with a dual core processor (intel).
I have a machine at home with a dual core processor (amd).
Both machines run linux, and both machines can successfully compile and run the MPI code locally (i.e. using 2 cores).
Now, is it possible to link the two machines together via MPI, so that I can utilise all 4 cores, bearing in mind the different architectures, and bearing in mind the fact that there are no shared (networked) filesystems?
If so, how?
Thanks,
Ben.
| Its possible to do this. Most MPI implementations allow you to specify the location of the binary to be run on different machines. Alternatively, make sure that it is in your path on both machines. Since both machines have the same byte order, that shouldn't be a problem. You will have to make sure that any input data that the individual processes read is available in both locations.
There are lots of complications with doing this. You need to make sure that the firewalls between the systems will allow process startup and communication. Communication between the machines is going to be much slower, so if you code is communication heavy or latency intolerant, it probably will be quite slow. Most likely your execution time running on all 4 cores will be longer than just running with 2 on a single machine.
|
3,062,746 | 3,062,783 | Special simple random number generator | How to create a function, which on every call generates a random integer number? This number must be most random as possible (according to uniform distribution). It is only allowed to use one static variable and at most 3 elementary steps, where each step consists of only one basic arithmetic operation of arity 1 or 2.
Example:
int myrandom(void){
static int x;
x = some_step1;
x = some_step2;
x = some_step3;
return x;
}
Basic arithmetic operations are +,-,%,and, not, xor, or, left shift, right shift, multiplication and division. Of course, no rand(), random() or similar stuff is allowed.
| Linear congruential generators are one of the oldest and simplest methods:
int seed = 123456789;
int rand()
{
seed = (a * seed + c) % m;
return seed;
}
Only a few instruction with basic arithmetic operations, that's all you need.
Mind that this algorithm works fine only if a, c and m are chosen in a particular way!
To guarantee the longest possible period of this sequence, c and m should be coprime, a − 1 should be divisible by all prime factors of m, and also for 4 if m is divisible by 4.
Some examples of parameters are shown on Wikipedia: for example ANSI C for some compilers proposes m = 2 ³¹, a = 1103515245 and c = 12345.
|
3,062,803 | 3,073,354 | How do I cleanly reconnect a boost::socket following a disconnect? | My client application uses a boost::asio::ip::tcp::socket to connect to a remote server.
If the app loses connection to this server (e.g. due to the server crashing or being shutdown) I would like it to attempt a re-connect at regular intervals until it succeeds.
What do I need to do on the client-side to cleanly handle a disconnect, tidy up and then repeatedly attempt reconnects?
Currently the interesting bits of my code look something like this.
I connect like this:
bool MyClient::myconnect()
{
bool isConnected = false;
// Attempt connection
socket.connect(server_endpoint, errorcode);
if (errorcode)
{
cerr << "Connection failed: " << errorcode.message() << endl;
mydisconnect();
}
else
{
isConnected = true;
// Connected so setup async read for an incoming message.
startReadMessage();
// And start the io_service_thread
io_service_thread = new boost::thread(
boost::bind(&MyClient::runIOService, this, boost::ref(io_service)));
}
return (isConnected)
}
Where the runIOServer() method is just:
void MyClient::runIOService(boost::asio::io_service& io_service)
{
size_t executedCount = io_service.run();
cout << "io_service: " << executedCount << " handlers executed." << endl;
io_service.reset();
}
And if any of the async read handlers return an error then they just call this disconnect method:
void MyClient::mydisconnect(void)
{
boost::system::error_code errorcode;
if (socket.is_open())
{
// Boost documentation recommends calling shutdown first
// for "graceful" closing of socket.
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorcode);
if (errorcode)
{
cerr << "socket.shutdown error: " << errorcode.message() << endl;
}
socket.close(errorcode);
if (errorcode)
{
cerr << "socket.close error: " << errorcode.message() << endl;
}
// Notify the observer we have disconnected
myObserver->disconnected();
}
..which attempts to gracefully disconnect and then notifies an observer, which will start calling connect() at five second intervals until it gets reconnected.
Is there anything else I need to do?
Currently this does seem to work. If I kill the server that it is connected to I get the expected "End of file" error at my read handlers and mydisconnect() is called without any issues.
But when it then attempts to re-connect and fails I see it report "socket.shutdown error: Invalid argument". Is this just because I am attempting to shutdown a socket that has no read/writes pending on it? Or is it something more?
| You need to create a new boost::asio::ip::tcp::socket each time you reconnect. The easiest way to do this is probably to just allocate the socket on the heap using a boost::shared_ptr (you could probably also get away with scoped_ptr if your socket is entirely encapsulated within a class). E.g.:
bool MyClient::myconnect()
{
bool isConnected = false;
// Attempt connection
// socket is of type boost::shared_ptr<boost::asio::ip::tcp::socket>
socket.reset(new boost::asio::ip::tcp::socket(...));
socket->connect(server_endpoint, errorcode);
// ...
}
Then, when mydisconnect is called, you could deallocate the socket:
void MyClient::mydisconnect(void)
{
// ...
// deallocate socket. will close any open descriptors
socket.reset();
}
The error you're seeing is probably a result of the OS cleaning up the file descriptor after you've called close. When you call close and then try to connect on the same socket, you're probably trying to connect an invalid file descriptor. At this point you should see an error message starting with "Connection failed: ..." based on your logic, but you then call mydisconnect which is probably then attempting to call shutdown on an invalid file descriptor. Vicious cycle!
|
3,062,931 | 3,064,855 | Does speed of an C/C++, Windows console application depend on whether the target is 32 or 64 bit? | Supposing that memory is not an issue does targeting a 64 bit OS make a C/C++ Windows console application run faster?
Update: Prompted by a few comments/answers the application involves statistical algorithms (e.g., linear algebra, random number draws etc).
| Replying mostly to the edit, not the original question: I've ported one application that's heavy on statistics and (especially) linear algebra to run as 64-bit code. For that code, the effort was minimal, and we got about a 3:1 improvement in speed.
I suspect that the majority of the notion that there often won't be comes (usually indirectly) from companies who have code that won't be easy to port, and are doing their best to tell customers why it's a good idea to continue buying their program, even though it's still 32-bit code. Of the code I've ported (or just "recompiled" in most cases) none has come out any slower as 64-bit code, and most has come out at least a little faster.
|
3,062,987 | 3,063,187 | Where can I find some in-depth DirectX 11 tutorials? | So far the only tutorials I've been able to find are on directx11tutorials.com, which are essentially inferred from the existing samples. Does anyone know where to find other tutorials, or better yet open source projects using DirectX 11? (Extra points for project code using DirectX 11 :) )
| I think there are still no DX11 tutorials / books. If you want to study DirectX in-depth, you could grab some DX10 book and also examine DX11 SDK and MSDN.
There is nothing really new in DirectX 11 (in application architecture / code building principles), so you could examine new API features and (if you're actually proficient with DirectX), getting used to them should not be very hard.
In this case you simply won't need any tutorials.
If you need some actual code samples, this (and other DX11 searches) could probably help you.
|
3,063,110 | 8,556,254 | Get the current operating system during runtime in C++ | I need to figure out the operating system my program is running on during runtime.
I'm using Qt 4.6.2, MinGW and Eclipse with CDT. My program shall run a command-line QProcess on Windows or Linux. Now I need a kind of switch to run the different code depending on the operating system.
| Actually the Operating System is defined by the Q_OS_... macros. Just saying. The Q_WS_... are windowing system. Not exactly the same. (I'm just reading what the author of the question wrote.... "operating system".)
These declarations are found in the qglobal.h file.
Use Q_OS_x with x being one of:
DARWIN - Darwin OS (synonym for Q_OS_MAC)
SYMBIAN - Symbian
MSDOS - MS-DOS and Windows
OS2 - OS/2
OS2EMX - XFree86 on OS/2 (not PM)
WIN32 - Win32 (Windows 2000/XP/Vista/7 and Windows Server 2003/2008)
WINCE - WinCE (Windows CE 5.0)
CYGWIN - Cygwin
SOLARIS - Sun Solaris
HPUX - HP-UX
ULTRIX - DEC Ultrix
LINUX - Linux
FREEBSD - FreeBSD
NETBSD - NetBSD
OPENBSD - OpenBSD
BSDI - BSD/OS
IRIX - SGI Irix
OSF - HP Tru64 UNIX
SCO - SCO OpenServer 5
UNIXWARE - UnixWare 7, Open UNIX 8
AIX - AIX
HURD - GNU Hurd
DGUX - DG/UX
RELIANT - Reliant UNIX
DYNIX - DYNIX/ptx
QNX - QNX
QNX6 - QNX RTP 6.1
LYNX - LynxOS
BSD4 - Any BSD 4.4 system
UNIX - Any UNIX BSD/SYSV system
The window system definitions are like this:
Use Q_WS_x where x is one of:
MACX - Mac OS X
MAC9 - Mac OS 9
QWS - Qt for Embedded Linux
WIN32 - Windows
X11 - X Window System
S60 - Symbian S60
PM - unsupported
WIN16 - unsupported
One of the main problems with using #ifdef is to make sure that if you compile on a "new" platform (never compiled that software on that platform) then you want to use #elif defined(...) and at least an #else + #error ...
#ifdef Q_OS_LINUX
std::cout << "Linux version";
#elif defined(Q_OS_CYGWIN)
std::cout << "Cygwin version";
#else
#error "We don't support that version yet..."
#endif
|
3,063,341 | 3,063,401 | Can a destructor be recursive? | Is this program well-defined, and if not, why exactly?
#include <iostream>
#include <new>
struct X {
int cnt;
X (int i) : cnt(i) {}
~X() {
std::cout << "destructor called, cnt=" << cnt << std::endl;
if ( cnt-- > 0 )
this->X::~X(); // explicit recursive call to dtor
}
};
int main()
{
char* buf = new char[sizeof(X)];
X* p = new(buf) X(7);
p->X::~X(); // explicit call to dtor
delete[] buf;
}
My reasoning: although invoking a destructor twice is undefined behavior, per 12.4/14, what it says exactly is this:
the behavior is undefined if the
destructor is invoked for an object
whose lifetime has ended
Which does not seem to prohibit recursive calls. While the destructor for an object is executing, the object's lifetime has not yet ended, thus it's not UB to invoke the destructor again. On the other hand, 12.4/6 says:
After executing the body [...] a
destructor for class X calls the
destructors for X's direct members,
the destructors for X's direct base
classes [...]
which means that after the return from a recursive invocation of a destructor, all member and base class destructors will have been called, and calling them again when returning to the previous level of recursion would be UB. Therefore, a class with no base and only POD members can have a recursive destructor without UB. Am I right?
| The answer is no, because of the definition of "lifetime" in §3.8/1:
The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.
As soon as the destructor is called (the first time), the lifetime of the object has ended. Thus, if you call the destructor for the object from within the destructor, the behavior is undefined, per §12.4/6:
the behavior is undefined if the destructor is invoked for an object whose lifetime has ended
|
3,063,514 | 3,063,552 | What does it mean to pass a &variable to a function? E.g., string& insert ( size_t pos1, const string& str ); | I understand passing a pointer, and returning a pointer:
char * strcat ( char * destination, const char * source );
You're passing a variable that contains the address to a char; returning the same.
But what does it mean to pass something using the reference operator? Or to return it?
string& insert ( size_t pos1, const string& str );
I mean, I understand what actually happens, I just don't understand the notation. Why isn't the notation this instead:
string * insert ( size_t pos1, const string * str ); //made up
I presume it has something to do with passing/returning the instance of a class, but what? Is this syntax valid; if not why not and if so what does it mean?
char & strcat ( char & destination, const char & source ); //made up
(all of the function declarations, except the last made-up two, are from http://www.cplusplus.com )
| Simply said, a reference is a pointer without telling you it's a pointer.
If you would write the following in plain C:
void getpi (float *f)
{
*f = 3.14;
}
float v;
getpi(&v);
You can write the following in C++ using references:
void getpi (float &f)
{
f = 3.14;
}
float v;
getpi(v);
It has the additional advantage that you can move from normal by-value argument to by-reference argument, without making changes to the caller. Suppose you have this:
class X; // A rather small class that can be easily copied
void doSomething (X x);
But after a while, class X becomes really big and you don't want to pass it by value anymore.
In plain C you have to change the argument to a pointer argument, and change all the callers.
In C++ you can simply do this:
void doSomething (X &x);
And you don't have to change any of the callers.
|
3,063,534 | 3,063,881 | Can I pass a pointer to a superclass, but create a copy of the child? | I have a function that takes a pointer to a superclass and performs operations on it. However, at some point, the function must make a deep copy of the inputted object. Is there any way I can perform such a copy?
It occurred to me to make the function a template function and simply have the user pass the type, but I hold out hope that C++ offers a more elegant solution.
| SpaceCowboy proposes the idiomatic clone method, but overlooked 3 crucial details:
class Super
{
public:
virtual Super* clone() const { return new Super(*this); }
};
class Child: public Super
{
public:
virtual Child* clone() const { return new Child(*this); }
};
clone is a const method
clone returns a pointer to the current class, not the base class
clone returns a copy of the current object
The 2nd is very important, because it allows use to benefit from the fact that sometimes you have more type information than just a Super*.
Also, I usually prefer clone to provide a copy, and not merely a new object of the same type. Otherwise you're using an Exemplar pattern to build new objects, but you're not cloning proper and the name is misleading.
|
3,063,611 | 3,063,658 | Just how much do I want to make virtual? | I am writing an abstract superclass where literally every method is going to be overridden. There is some default functionality I could implement, but most of the time it's enough to leave the implementation to the subclass writer.
Since just about every method is going to be overwritten, how much should I make virtual and how much should I just leave as regular methods? In the current incarnation, everything is virtual, but I still haven't let this loose to anyone to use, so the design is flexible.
What advantages/disadvantages are there to virtual functions? Links to good reading material about this would be appreciated.
| Virtual function calls are slower than non-virtual ones, but if you need runtime polymorphism, there's no alternative. Virtual function calls have a roughly constant overhead regardless of how many you have, so there's little disadvantage. You can see the design of many professional classes- like IDirect3D9Device- have many, many virtual methods in one class.
|
3,063,690 | 3,063,938 | I have a bunch of template parameters that I want to hide from my users. How can I do this? | I have a superclass which is defined in terms of a few internal types it uses. Subclassing is performed as so:
template <class InternalType1, class InternalType2>
class Super
{
...
}
class Sub : Super <interalTypeClass1, interalTypeClass2>
{
...
}
But when I want to write a function that takes a pointer to the superclass, this happens :
template <class InternalType1, class InternalType2>
void function(Super<InternalType1, InternalType2>* in) { ... }
The user really shouldn't know anything about the inside classes, and should really just concern himself with the use of the function. Some of these template lists become very very large, and expecting the user to pass them every time is wasteful, in my opinion.
Any suggestions?
EDIT: The function needs to know the internal types in use, so unless there is a way to access template types at compile time, I think there is no solution?
Potential solution: Have each class do the following:
#define SubTemplateArgs <SubTypeName, SubInternalType1, SubInternalType2>
?
| template <class TInternal1, TInternal2>
class Super {
private:
/*...*/
public:
typedef TInternal1 internal_type_1;
typedef TInternal2 internal_type_2;
/*...*/
};
typedef Super<int, char> IntCharSuper;
typedef Super<bool, char> BoolCharSuper;
class Sub1 : IntCharSuper {/*...*/};
class Sub2 : IntCharSuper {/*...*/};
class Sub3 : BoolCharSuper {/*...*/};
/***
* functionA (below) can only take a pointer to an object of a
* class which inherits from IntCharSuper
**/
void functionA(IntCharSuper* in){
IntCharSuper::internal_type_1 internal1_variable;
IntCharSuper::internal_type_2 internal2_variable;
// we now have 2 variables of the internal types...
}
/***
* functionB (below) can take a pointer to an object of a class which inherits from any kind of Super,
* no matter what the template parameters of that Super are.
* so functionB will work for types which inherit from
* IntCharSuper, BoolCharSuper, Super<YourCustomType, void*>, or anything else for TInternal1 and TInternal2.
**/
template <class TSuper>
void functionB(TSuper* in) {
typename TSuper::internal_type_1 internal1_variable; /* typename is needed here */
typename TSuper::internal_type_2 internal2_variable; /* typename is needed here */
// we now have 2 variables of the internal types...
}
int main(int argc, const char* argv) {
Sub1 s1;
Sub2 s2;
Sub3 s3;
functionA(&s1); //OK, s1 inherits IntCharSuper
functionA(&s2); //OK, s2 inherits IntCharSuper
functionA(&s3); //ERROR, s3 hasnt got IntCharSuper as parent
functionB(&s2); //OK, s2 inherits from a class which defines internal_type_1 and internal_type_2
functionB(&s3); //OK, s3 inherits from a class which defines internal_type_1 and internal_type_2
return 0;
}
|
3,063,800 | 3,063,853 | I can't put a string in a switch nor an array in a class | Okay, im making a pretty big file in my opinion, so i wanted to separate it into several files for cleaner code. so i have my main .cpp file and two header files holding my classes. well the header files dont hold strings, it aboslutely wont budge. i call the library in both my .cpp file and even tried it in my header file.
another issue i ran into is using strings to make switches function, reason being if i use integers in a switch if the user inputs a alphabetical character the program goes into an endless loop.
string choice;
switch (choice)
{
case "1" :
//...
break;
case "2" :
//...
break;
}
and my last issue is when i create an object in a case it gives an error. says cross initialization of object.
string choice;
switch (choice)
{
case "1" :
Class object;
break;
case "2" :
//...
break;
}
Here is the header issue im having.
///main.cpp////
#include <iostream>
#include <string>
#include "customer.h"
//// customer.h ////
class Customer
{
string name;
string meal;
// method
public:
int Choose_cCustomer()
{
int a;
a = rand () % (10 - 1 + 1) + 1;
return a;
};
complier code : 'string' does not name a type;
|
"string" does not name a type
Add #include <string> at the top of your header file, since it is used in the header file, it must be included first. Since string is defined in the std namespace, you should declare it with std::string name;.
In the cpp file, you can shortcut with using namespace std;, but it might be best practice to always refer to the qualified name (the "qualified name" includes the namespace - e.g. std::string or std::vector).
I cannot do switch(string)
That is correct, switches are reserved for "integral values". Or values that can be treated as integral (e.g. characters). See (http://www.cprogramming.com/tutorial/lesson5.html)
I cannot do case 1: Class object;
That is sort-of correct. A case cannot directly have variables declared in it. However, there is a quick workaround:
case 1: { // Notice the added braces, to create a 'scope' for which to define object.
Class object;
// ... use object as normal ...
break;
}
If you really want to compare strings, you should chain if () { } else if () { } else { } statements.
|
3,063,834 | 3,064,055 | Function returning MYSQL_ROW | I'm working on a system using lots of MySQL queries and I'm running into some memory problems I'm pretty sure have to do with me not handling pointers right...
Basically, I've got something like this:
MYSQL_ROW function1() {
string query="SELECT * FROM table limit 1;";
MYSQL_ROW return_row;
mysql_init(&connection); // "connection" is a global variable
if (mysql_real_connect(&connection,HOST,USER,PASS,DB,0,NULL,0)){
if (mysql_query(&connection,query.c_str()))
cout << "Error: " << mysql_error(&connection);
else{
resp = mysql_store_result(&connection); //"resp" is also global
if (resp) return_row = mysql_fetch_row(resp);
mysql_free_result(resp);
}
mysql_close(&connection);
}else{
cout << "connection failed\n";
if (mysql_errno(&connection))
cout << "Error: " << mysql_errno(&connection) << " " << mysql_error(&connection);
}
return return_row;
}
And function2():
MYSQL_ROW function2(MYSQL_ROW row) {
string query = "select * from table2 where code = '" + string(row[2]) + "'";
MYSQL_ROW retorno;
mysql_init(&connection);
if (mysql_real_connect(&connection,HOST,USER,PASS,DB,0,NULL,0)){
if (mysql_query(&connection,query.c_str()))
cout << "Error: " << mysql_error(&conexao);
else{
// My "debugging" shows me at this point `row[2]` is already fubar
resp = mysql_store_result(&connection);
if (resp) return_row = mysql_fetch_row(resp);
mysql_free_result(resp);
}
mysql_close(&connection);
}else{
cout << "connection failed\n";
if (mysql_errno(&connection))
cout << "Error : " << mysql_errno(&connection) << " " << mysql_error(&connection);
}
return return_row;
}
And main() is an infinite loop basically like this:
int main( int argc, char* args[] ){
MYSQL_ROW row = NULL;
while (1) {
row = function1();
if(row != NULL) function2(row);
}
}
(variable and function names have been generalized to protect the innocent)
But after the 3rd or 4th call to function2, that only uses row for reading, row starts losing its value coming to a segfault error...
Anyone's got any ideas why? I'm not sure the amount of global variables in this code is any good, but I didn't design it and only got until tomorrow to fix and finish it, so workarounds are welcome!
Thanks!
| Update: I misunderstood how mysql results are used. It looks like the row pointer array points to the results array which you free in function1() and then use it in function2() after it has been returned to the heap.
What you need to do is copy return_row[2] to a persistent string before freeing the results. Then pass that on to function2(). I see you doing something similar in function2() so you need to fix it there as well (though in your example you aren't doing anything with its return value).
Also, you are correct that free(row); is not the correct thing to do.
|
3,063,973 | 3,064,026 | Generating code at compile-time using scripts | I would ideally like to be able to add (very repetitive) C/C++ code to my actual code, but at compile time, code which would come from say, the stdout of a python script, the same way one does with macros.
For example, let's say I want to have functions that depend on the public attributes of a given class, being able to just write the following in my C++ code would be a blessing:
generate_boring_functions(FooBarClass,"FooBarClass.cpp")
Is that feasible using conventional means? Or must I hack with Makefiles and temporary source files?
Thanks.
| You do most likely need to tweak the Makefile a bit. It would be easy to write a (Python) script that reads each of your source files as an additional preprocessing step, replacing instances of generate_boring_functions (or any other script-macro) with the correct code, potentially just by invoking generate_boring_functions.py with the right arguments, and bypassing the need for temporary files by sending the source to the compiler over standard input.
Damn, now I want to make something like this.
Edit: A rule like this, stuck in a makefile, could be used to handle the extra build step. This is untested and added only for some shot at completeness.
%.o : %.cpp
python macros.py $< | g++ -x cpp -c - -o $@
|
3,063,987 | 3,064,039 | need help with C++ using maps to keep track of words in a INPUT file | Let say i have a text file with
today is today but
tomorrow is today tomorrow
then using maps how can i keep track of the words that are repeated? and on which line it repeats?
so far i have each string in the file read in as a temp and it is stored in the following way:
map<string,int> storage;
int count = 1 // for the first line of the file
if(infile.is_open()){
while( !infile.eof() ){
getline(in, line);
istringstream my_string(line);
while(my_string.good()){
string temp;
my_string >> temp;
storage[temp] = count
}
count++;// so that every string read in the next line will be recorded as that line.
}
}
map<string,int>::iterator m;
for(int m = storage.begin(); m!= storage.end(); m++){
out<<m->first<<": "<<"line "<<m->second<<endl;
}
right now the output is just
but: line 1
is: line 2
today: line 2
tomorrow: line 2
But instead..
it should print out(no repeating strings):
today : line 1 occurred 2 times, line 2 occurred 1 time.
is: line 1 occurred 1 time, line 2 occurred 1 time.
but: line 1 occurred 1 time.
tomorrow: line 2 occurred 2 times.
Note: the order of the string does not matter.
Any help would be appreciated. Thanks.
| map stores a (key, value) pair with a unique key. Meaning that if you assign to the same key more than once, only the last value that you assigned will be stored.
Sounds like what you want to do is instead of storing the line as the value, you want to store another map of lines->occurances.
So you could make your map like this:
typedef int LineNumber;
typedef int WordHits;
typedef map< LineNumber, WordHits> LineHitsMap;
typedef map< string, LineHitsMap > WordHitsMap;
WordHitsMap storage;
Then to insert:
WordHitsMap::iterator wordIt = storage.find(temp);
if(wordIt != storage.end())
{
LineHitsMap::iterator lineIt = (*wordIt).second.find(count);
if(lineIt != (*wordIt).second.end())
{
(*lineIt).second++;
}
else
{
(*wordIt).second[count] = 1;
}
}
else
{
LineHitsMap lineHitsMap;
lineHitsMap[count] = 1;
storage[temp] = lineHitsMap;
}
|
3,064,052 | 3,064,412 | C++ project type: unicode vs multi-byte; pros and cons | I'm wondering what the Stack Overflow community thinks when it comes to creating a project (thinking primarily c++ here) with a unicode or a multi-byte character set.
Are there pros to going Unicode
straight from the start, implying all
your strings will be in wide format?
Are there performance issues / larger
memory requirements because of a
standard use of a larger character?
Is there an advantage to this method?
Do some processor architectures
handle wide characters better?
Are there any reasons to make your
project Unicode if you don't plan on
supporting additional languages?
What reasons would one have for creating a project with a multi-byte character set?
How do all of the factors above collide in a high performance environment (such as a modern video game) ?
| Two issues I'd comment on.
First, you don't mention what platform you're targeting. Although recent Windows versions (Win2000, WinXP, Vista and Win7) support both Multibyte and Unicode versions of system calls using strings, the Unicode versions are faster (the multibyte versions are wrappers that convert to Unicode, call the Unicode version, then convert any returned strings back to mutlibyte). So if you're making a lot of these types of calls the Unicode will be faster.
Just because you're not planning on explicitly supporting additional languages, you should still consider supporting Unicode if your application saves and displays text entered by the users. Just because your application is unilingual, it doesn't follow that all it's users will be unilingual too. They may be perfectly happy to use your English language GUI, but might want to enter names, comments or other text in their own language and have them displayed properly.
|
3,064,062 | 3,064,324 | C# & C++, runtime error when call C++ dll from C# | I have written a C++ wrapper DLL for C# to call. The DLL was tested and worked fine with my C++ test program.
now integrated with C#, I got runtime error and crashed. Cannot use debugger to see more details.
The C++ side has only one method:
#ifdef DLLWRAPPERWIN32_EXPORTS
#define DLLWRAPPERWIN32_API __declspec(dllexport)
#else
#define DLLWRAPPERWIN32_API __declspec(dllimport)
#endif
#include "NB_DPSM.h"
extern "C" {
DLLWRAPPERWIN32_API int WriteGenbenchDataWrapper(string fileNameToAnalyze,
string parameterFileName,
string baseNameToSaveData,
string logFileName,
string& message) ;
}
in the C# side, there is a definition,
[DllImport("..\\..\\thirdParty\\cogs\\DLLWrapperWin32.dll")]
public static extern int WriteGenbenchDataWrapper(string fileNameToAnalyze,
string parameterFileName,
string baseNameToSaveData,
string logFileName,
ref string message);
and a call:
string msg = "";
int returnVal = WriteGenbenchDataWrapper(rawDataFileName,
parameterFileName, outputBaseName, logFileName, ref msg);
I guess there must be something wrong with the last parameter of the function. string& in C++ should be ref string in C#?
EDIT:
Do we really need the extern "C"?
EDIT 2:
after I remove the extern "C from the dll, I got the EntryPointNotFoundException. When I look at the dll by using DLL Export Viewer, I found the function name is "int __cdecl WriteGenbenchDataWrapper(class std:: ..." Do I need to include the " __cdecl"?
| There are a bunch of rules for marsheling with PInvoke.
For reference Marsheling between managaed & unmanaged
Focusing on the C# side first.
If you knew a reasonable size of the message up front you could use StringBuilder type and define that size, something like.
[DllImport("DLLWrapperWin32.dll")]
public static extern int WriteGenbenchDataWrapper(string fileNameToAnalyze,
string parameterFileName,
string baseNameToSaveData,
string logFileName,
StringBuilder message
int messageLength );
Impression from the name message (and other posts) indiciates you don't know the size up front, and you won't be passing a partial message to the function so maybe
[DllImport("DLLWrapperWin32.dll")]
public static extern int WriteGenbenchDataWrapper(in string fileNameToAnalyze,
in string parameterFileName,
in string baseNameToSaveData,
in string logFileName,
out string message );
Now on the C/C++ side - to match the second definition
extern "C" // if this is a C++ file to turn off name mangling for this function only
int WriteGenbenchDataWrapper( char * fileNameToAnalyze,
char * parameterFileName,
char * baseNameToSaveData,
char * logFileName,
char ** message ) {
string internalMessage;
SomeFunc( internalMessage ); // these functions won't have extern "C" applied
* message = (char *)::CoTaskMemAlloc(internalMessage.length()+1);
strcpy(* message, internalMessage.c_str());
}
Consideration of unicode/ansi strings is also important, refer to [MarshalAsAttribute(UnmanagedType.LPWSTR)]
For release mode you will want to remove your development path settings "..\..\thirdParty\cogs"
|
3,064,237 | 3,064,262 | C++: Maybe you know this pitfall? | I'm developing a game. I have a header GameSystem (just methods like the game loop, no class) with two variables:
int mouseX and int mouseY. These are updated in my game loop. Now I want to access them from Game.cpp file (a class built by a header-file and the source-file). So, I #include "GameSystem.h" in Game.h. After doing this I get a lot of compile errors. When I remove the include he says of course:
Game.cpp:33: error: ‘mouseX’ was not declared in this scope
Game.cpp:34: error: ‘mouseY’ was not declared in this scope
Where I want to access mouseX and mouseY.
All my .h files have Header Guards, generated by Eclipse.
I'm using SDL and if I remove the lines that wants to access the variables, everything compiles and run perfectly (*).
I hope you can help me...
This is the error-log when I #include "GameSystem.h" (All the code he is refering to works, like explained by the (*)):
In file included from ../trunk/source/domein/Game.h:14,
from ../trunk/source/domein/Game.cpp:8:
../trunk/source/domein/GameSystem.h:30: error: expected constructor, destructor, or type conversion before ‘*’ token
../trunk/source/domein/GameSystem.h:46: error: variable or field ‘InitGame’ declared void
../trunk/source/domein/GameSystem.h:46: error: ‘Game’ was not declared in this scope
../trunk/source/domein/GameSystem.h:46: error: ‘g’ was not declared in this scope
../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘char’
../trunk/source/domein/GameSystem.h:46: error: expected primary-expression before ‘bool’
../trunk/source/domein/FPS.h:46: warning: ‘void FPS_SleepMilliseconds(int)’ defined but not used
This is the code which try to access the two variables:
SDL_Rect pointer;
pointer.x = mouseX;
pointer.y = mouseY;
pointer.w = 3;
pointer.h = 3;
SDL_FillRect(buffer, &pointer, 0xFF0000);
| In your GameSystem header, don't define those variables as:
int mouseX;
int mouseY;
instead, you should declare them:
extern int mouseX;
extern int mouseY;
Then in one of your .cpp files you define them:
int mouseX;
int mouseY;
The problem with defining them in a header file is that the compiler will try to instantiate them in every single .cpp where you include the header.
|
3,064,509 | 3,064,568 | Cast from Void* to TYPE* using C++ style cast: static_cast or reinterpret_cast | So if your converting from Void* to Type* or from Type* to Void* should you use:
void func(void *p)
{
Params *params = static_cast<Params*>(p);
}
or
void func(void *p)
{
Params *params = reinterpret_cast<Params*>(p);
}
To me static_cast seems the more correct but I've seen both used for the same purpose. Also, does the direction of the conversion matter. i.e. should I still use static_cast for:
_beginthread(func,0,static_cast<void*>(params)
I have read the other questions on C++ style casting but I'm still not sure what the correct way is for this scenario (I think it is static_cast)
| You should use static_cast so that the pointer is correctly manipulated to point at the correct location. However, you should only do this if you used static cast to cast the pointer to void* in the first place. Otherwise you should reinterpret_cast to exactly the same type of the original pointer (no bases or such).
|
3,064,559 | 3,064,579 | How is vector implemented in C++ | I am thinking of how I can implement std::vector from the ground up.
How does it resize the vector?
realloc only seems to work for plain old stucts, or am I wrong?
| it is a simple templated class which wraps a native array. It does not use malloc/realloc. Instead, it uses the passed allocator (which by default is std::allocator).
Resizing is done by allocating a new array and copy constructing each element in the new array from the old one (this way it is safe for non-POD objects). To avoid frequent allocations, often they follow a non-linear growth pattern.
UPDATE: in C++11, the elements will be moved instead of copy constructed if it is possible for the stored type.
In addition to this, it will need to store the current "size" and "capacity". Size is how many elements are actually in the vector. Capacity is how many could be in the vector.
So as a starting point a vector will need to look somewhat like this:
template <class T, class A = std::allocator<T> >
class vector {
public:
// public member functions
private:
T* data_;
typename A::size_type capacity_;
typename A::size_type size_;
A allocator_;
};
The other common implementation is to store pointers to the different parts of the array. This cheapens the cost of end() (which no longer needs an addition) ever so slightly at the expense of a marginally more expensive size() call (which now needs a subtraction). In which case it could look like this:
template <class T, class A = std::allocator<T> >
class vector {
public:
// public member functions
private:
T* data_; // points to first element
T* end_capacity_; // points to one past internal storage
T* end_; // points to one past last element
A allocator_;
};
I believe gcc's libstdc++ uses the latter approach, but both approaches are equally valid and conforming.
NOTE: This is ignoring a common optimization where the empty base class optimization is used for the allocator. I think that is a quality of implementation detail, and not a matter of correctness.
|
3,064,668 | 3,094,248 | A good ORM to use with qt4 (c++) ? (Django like...) | Does anyone have a recommendation for an ORM for qt4 (c++)? (Like a Django ORM).
| I would suggest you take a look at the QDjango ORM, it might be just what you are looking for. This C++ ORM only depends on Qt and builds upon Qt's Meta-Object System to provide introspection. On top of the basic create/update/delete operations at the model level, it provides a queryset template class (modeled after django's querysets) which allows to build fairly complex lookups.
Optional QtScript support is also provided, so you can access your models and perform database queries from scripts.
|
3,064,926 | 3,064,939 | How to write log base(2) in c/c++ | Is there any way to write log(base 2) function?
The C language has 2 built in function -->>
1.log which is base e.
2.log10 base 10;
But I need log function of base 2.How to calculate this.
| Simple math:
log2 (x) = logy (x) / logy (2)
where y can be anything, which for standard log functions is either 10 or e.
|
3,064,944 | 3,064,984 | DLL Export C/C++ 6.00 function invoked by VB6 | I have been attemptng to create a DLL with C/C++ that can be accessed by VB6, and that's right I get error "453 Can't find DLL entry point myFunctionName in myDllName.dll" upon calling the function from a VB6 app.
After searching the Web, including this site, I see that I am not alone, and I have tried the various solutions posted but error "453" is unexcapable.
This is Not a COMM dll, and I believe that is possible when created via C/C++.
In any case, please help, if you can. Please refer to the following simple test case below:
The DLL created as a C/C++ 6.00 Win32 Dynamic-Link Library:
#include <Windows.h>
// Note that I did try the line below rather than the def file, but to no avail...
// #pragma comment(linker, "/EXPORT:ibask32=_ibask32@0")
// Function definition
extern "C" int __declspec(dllexport) __stdcall ibask32()
{
MessageBox(NULL,"String","Sample Code", NULL);
return 0L;
}
The def file:
LIBRARY "Gpib-32"
EXPORTS
ibask32
Now for the VB App:
The following is the entire content of the startup Form1, Form_Load
Option Explicit
Private Sub Form_Load()
Call ibask
End Sub
The following is a BAS module file that is added to the project:
Option Explicit
Declare Function ibask32 Lib "Gpib-32.dll" Alias "ibask" () As Long
Sub ibask()
Call ibask32 ' Note: This is the point of failure
End Sub
Thanks in advance if a workable solution can be provided,
Tom
| You are doing everything right as near as I can tell. Verify your assumptions by running Dumpbin.exe /exports on the DLL. That shows the actual name of the exported function, it has to match the Alias in the VB6 declaration.
The only other failure mode I can think of is VB6 loading the wrong DLL. It has to be present in a directory listed on the PATH if you want to use it from the VB6 IDE. Verify by running "where gpib-32.dll" from the command line.
|
3,064,976 | 3,065,119 | Why have pointer parameters? |
Possible Duplicates:
Why use pointers?
Passing a modifiable parameter to c++ function
Why would I want to have pointer parameters? The only reason I can see is for small functions to attempt to reduce confusion and a smaller memory footprint.
| In Passing a modifiable parameter to c++ function I answered when to use a reference instead of a pointer.
Conversely, prefer a pointer to a reference when any of the following are true:
It can be null
It can be changed (to point to something else)
It must be deleted
Some people also prefer a pointer when the thing that's being pointed at should be mutated, saying that the difference between a const reference and a non-const reference isn't obvious enough to the reader.
|
3,065,092 | 3,065,211 | Check if a pointer points to allocated memory on the heap | I want to know if a pointer points to a piece of memory allocated with malloc/new. I realize that the answer for an arbitrary address is "No you can't" but I do think it is possible to override malloc/free and keep track of allocated memory ranges.
Do you know a memory management library providing this specific tool?
Do you know something for production code?
Valgrind is great, but it is too much instrumentation (slow) and as Will said we don't want to use Valgrind like this (making the soft crash is good enough).
Mudflap is a very good solution, but dedicated to GCC, and sadly, a check does not simply return a boolean (see my answer below).
Note that checking that memory writes are legal is a security issue. So looking for performance is motivated.
| There's no standard way to do this, but various malloc debugging tools may have a way of doing it. For example, if you use valgrind, you can use VALGRIND_CHECK_MEM_IS_ADDRESSABLE to check this and related things
|
3,065,109 | 3,073,077 | Can Boost Program_options separate comma separated argument values | If my command line is:
> prog --mylist=a,b,c
Can Boost's program_options be setup to see three distinct argument values for the mylist argument? I have configured program_options as:
namespace po = boost::program_options;
po::options_description opts("blah")
opts.add_options()
("mylist", std::vector<std::string>>()->multitoken, "description");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, opts), vm);
po::notify(vm);
When I check the value of the mylist argument, I see one value as a,b,c. I'd like to see three distinct values, split on comma. This works fine if I specify the command line as:
> prog --mylist=a b c
or
> prog --mylist=a --mylist=b --mylist=c
Is there a way to configure program_options so that it sees a,b,c as three values that should each be inserted into the vector, rather than one?
I am using boost 1.41, g++ 4.5.0 20100520, and have enabled c++0x experimental extensions.
EDIT:
The accepted solution works but ends up being more complicated, IMO, than just iterating through a vector and splitting the values manually. In the end, I took the suggestion from James McNellis and implemented it that way. His solution wasn't submitted as an answer, however, so I accepted the other correct solution from hkaiser. Both worked, but the manual tokenization is clearer.
| You could register a custom validator for your option:
namespace po = boost::program_options;
struct mylist_option
{
// values specified with --mylist will be stored here
vector<std::string> values;
// Function which validates additional tokens from command line.
static void
validate(boost::any &v, std::vector<std::string> const &tokens)
{
if (v.empty())
v = boost::any(mylist_option());
mylist_option *p = boost::any_cast<mylist_option>(&v);
BOOST_ASSERT(p);
boost::char_separator<char> sep(",");
BOOST_FOREACH(std::string const& t, tokens)
{
if (t.find(",")) {
// tokenize values and push them back onto p->values
boost::tokenizer<boost::char_separator<char> > tok(t, sep);
std::copy(tok.begin(), tok.end(),
std::back_inserter(p->values));
}
else {
// store value as is
p->values.push_back(t);
}
}
}
};
which then can be used as:
opts.add_options()
("mylist", po::value<mylist_option>()->multitoken(), "description");
and:
if (vm.count("mylist"))
{
// vm["mylist"].as<mylist_option>().values will hold the value specified
// using --mylist
}
|
3,065,154 | 3,087,312 | Undefined reference to vtable | When building my C++ program, I'm getting the error message
undefined reference to 'vtable...
What is the cause of this problem? How do I fix it?
It so happens that I'm getting the error for the following code (The class in question is CGameModule.) and I cannot for the life of me understand what the problem is. At first, I thought it was related to forgetting to give a virtual function a body, but as far as I understand, everything is all here. The inheritance chain is a little long, but here is the related source code. I'm not sure what other information I should provide.
Note: The constructor is where this error is happening, it'd seem.
My code:
class CGameModule : public CDasherModule {
public:
CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName)
: CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName)
{
g_pLogger->Log("Inside game module constructor");
m_pInterface = pInterface;
}
virtual ~CGameModule() {};
std::string GetTypedTarget();
std::string GetUntypedTarget();
bool DecorateView(CDasherView *pView) {
//g_pLogger->Log("Decorating the view");
return false;
}
void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; }
virtual void HandleEvent(Dasher::CEvent *pEvent);
private:
CDasherNode *pLastTypedNode;
CDasherNode *pNextTargetNode;
std::string m_sTargetString;
size_t m_stCurrentStringPos;
CDasherModel *m_pModel;
CDasherInterfaceBase *m_pInterface;
};
Inherits from...
class CDasherModule;
typedef std::vector<CDasherModule*>::size_type ModuleID_t;
/// \ingroup Core
/// @{
class CDasherModule : public Dasher::CDasherComponent {
public:
CDasherModule(Dasher::CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, ModuleID_t iID, int iType, const char *szName);
virtual ModuleID_t GetID();
virtual void SetID(ModuleID_t);
virtual int GetType();
virtual const char *GetName();
virtual bool GetSettings(SModuleSettings **pSettings, int *iCount) {
return false;
};
private:
ModuleID_t m_iID;
int m_iType;
const char *m_szName;
};
Which inherits from....
namespace Dasher {
class CEvent;
class CEventHandler;
class CDasherComponent;
};
/// \ingroup Core
/// @{
class Dasher::CDasherComponent {
public:
CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore);
virtual ~CDasherComponent();
void InsertEvent(Dasher::CEvent * pEvent);
virtual void HandleEvent(Dasher::CEvent * pEvent) {};
bool GetBoolParameter(int iParameter) const;
void SetBoolParameter(int iParameter, bool bValue) const;
long GetLongParameter(int iParameter) const;
void SetLongParameter(int iParameter, long lValue) const;
std::string GetStringParameter(int iParameter) const;
void SetStringParameter(int iParameter, const std::string & sValue) const;
ParameterType GetParameterType(int iParameter) const;
std::string GetParameterName(int iParameter) const;
protected:
Dasher::CEventHandler *m_pEventHandler;
CSettingsStore *m_pSettingsStore;
};
/// @}
#endif
| So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefile that had no idea about my new files whatsoever.
Thanks for the responses and the link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a real reason.
|
3,065,200 | 3,065,510 | Inheritence and usage of dynamic_cast | Suppose I have 3 classes as follows (as this is an example, it will not compile!):
class Base
{
public:
Base(){}
virtual ~Base(){}
virtual void DoSomething() = 0;
virtual void DoSomethingElse() = 0;
};
class Derived1
{
public:
Derived1(){}
virtual ~Derived1(){}
virtual void DoSomething(){ ... }
virtual void DoSomethingElse(){ ... }
virtual void SpecialD1DoSomething{ ... }
};
class Derived2
{
public:
Derived2(){}
virtual ~Derived2(){}
virtual void DoSomething(){ ... }
virtual void DoSomethingElse(){ ... }
virtual void SpecialD2DoSomething{ ... }
};
I want to create an instance of Derived1 or Derived2 depending on some setting that is not available until run-time.
As I cannot determine the derived type until run-time, then do you think the following is bad practice?...
class X
{
public:
....
void GetConfigurationValue()
{
....
// Get configuration setting, I need a "Derived1"
b = new Derived1();
// Now I want to call the special DoSomething for Derived1
(dynamic_cast<Derived1*>(b))->SpecialD1DoSomething();
}
private:
Base* b;
};
I have generally read that usage of dynamic_cast is bad, but as I said, I don't know
which type to create until run-time. Please help!
| Using dynamic_cast is not bad practice per se. It's bad practice to use it inappropriately, i.e. where it's not really needed.
It's also a bad practice to use it this way:
(dynamic_cast<Derived1*>(b))->SpecialD1DoSomething();
Reason: dynamic_cast(b) may return NULL.
When using dynamic_cast, you have to be extra careful, because it's not guaranteed, that b is actually of type Derived1 and not Derived2:
void GenericFunction(Base* p)
{
(dynamic_cast<Derived1*>(b))->SpecialD1DoSomething();
}
void InitiallyImplementedFunction()
{
Derived1 d1;
GenericFunction(&d1); // OK... But not for long.
// Especially, if implementation of GenericFunction is in another library
// with not source code available to even see its implementation
// -- just headers
}
void SomeOtherFunctionProbablyInAnotherUnitOfCompilation()
{
Derived2 d2;
GenericFunction(&d2); // oops!
}
You have to check if dynamic_cast is actually successful. There are two ways of doing it: checking it before and after the cast. Before the cast you can check if the pointer you're trying to cast is actually the one you expect via RTTI:
if (typeid(b) == typeid(Derived1*))
{
// in this case it's safe to call the function right
// away without additional checks
dynamic_cast<Derived1*>(b)->SpecialD1DoSomething();
}
else
{
// do something else, like try to cast to Derived2 and then call
// Derived2::SpecialD2DoSomething() in a similar fashion
}
Checking it post-factum is actually a bit simpler:
Derived1* d1 = dynamic_cast<Derived1*>(b);
if (d1 != NULL)
{
d1->SpecialD1DoSomething();
}
I'd also say it's a bad practice to try and save typing while programming in C++. There are many features in C++ than seem to be completely fine to be typed shorter (i.e. makes you feel 'that NULL will never happen here'), but turn out to be a pain in the ass to debug afterwards. ;)
|
3,065,221 | 3,065,259 | Moving from Java to C++ API's | There are some particular API's in Java that make it very good. However I would prefer C++ because of performance and "bleeding" edge support with OpenGL and OpenAL among the many libraries.
Which API's are there that are similar to Java2D (I know I can use OpenGL however I lack the matrix math understanding to fully use OpenGL in this way)? Also which GUI framework (non-native; platform independent) is the most used in C++?
| FLTK, Fast Light Tool Kit has some 2d functionality. It's somewhat like swing and 2d mixed together. It does focus more on the UI aspect but it may help you out.
http://www.fltk.org/
|
3,065,284 | 3,065,308 | What happens when I throw an exception? | I have some technical questions. In this function:
string report() const {
if(list.begin() == list.end()){
throw "not good";
}
//do something
}
If I throw the exception what is going on with the program? Will my function terminate or will it run further? If it terminates, what value will it return?
| If you throw an exception, all functions will be exited back to the point where it finds a try...catch block with a matching catch type. If your function isn't called from within a try block, the program will exit with an unhandled exception.
Check out https://isocpp.org/wiki/faq/exceptions for more info.
|
3,065,332 | 3,065,640 | Statically linked libraries not running code inside to setup static variables | In a c++ project I am working on, I have a simple c++ file that needs to run some code at the beginning of the program execution. This file is linked into a static library, which is then linked into the main program.
I have similar code in other files running fine, that looks something like:
bool ____nonexistent_value = executeAction();
However, it does not work inside this file unless I make use of a function implemented in this file. It does work if the library is compiled as a shared library. I'd prefer to link this statically as the library is only a convenience as the file is in a different directory.
Update (Solution):
For now creating shared instead of static libraries makes everything work. Later I will look into getting everything linking with static libraries. Thanks for everyone's help!
| If no symbol is referenced in that particular file then the file will not be included by the linker. You have two options:
Remove the file from library and include it (object or source file) directly in the command line for compilation/linking. Then the file should be included in executable.
Have a symbol in a file which you reference from from other files (for example the one with main() definition), this should "pull" the file during linking.
|
3,065,643 | 3,065,656 | <function> referenced from; symbol(s) not found | I have a piece of C code that is used from a C++ function. At the top of my C++ file I have the line: #include "prediction.h"
In prediction.h I have this:
#ifndef prediction
#define prediction
#include "structs.h"
typedef struct {
double estimation;
double variance;
} response;
response runPrediction(int obs, location* positions, double* observations,
int targets, location* targetPositions);
#endif
I also have prediction.c, which has:
#include "prediction.h"
response runPrediction(int obs, location* positions, double* observations,
int targets, location* targetPositions) {
// code here
}
Now, in my C++ file (which as I said includes prediction.h) I call that function, then compile (through Xcode) I get this error:
"runPrediction(int, location*, double*, int, location*)", referenced from:
mainFrame::respondTo(char*, int)in mainFrame.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
prediction.c is marked for compilation for the current target. I don't have any problems with other .cpp files not being compiled. Any thoughts here?
| Likely the name of the function is being mangled*. You need to do the following:
extern "C" response runPrediction(int obs, location* positions,
double* observations, int targets, location* targetPositions);
Which tells it to treat it as a C function declaration.
*C++ mangles function names to give them unique names during the linking phase, for function overloading. C has no function overloading so does no such thing.
Just so you know, you can also make an extern "C" block, if you have multiple things to extern:
extern "C"
{
response runPrediction(int obs, location* positions,
double* observations, int targets, location* targetPositions);
// other stuff
}
And like Paul suggests, to allow the header to be used in both use __cplusplus to condition it:
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif
EXTERN_C response runPrediction(int obs, location* positions,
double* observations, int targets, location* targetPositions);
|
3,065,708 | 3,065,794 | strict string to int[long] | Do we have a standard way of converting a char* to int (or long) in a strict way, i.e. we should get proper result only if all characters are digits and can fit in an int (or long) -- some way by using strtol etc.. ?
Thus "sbc45", "4590k", " 56", "56 ", should be all invalid using that function.
| This is a version close to what @GMan did, but it doesn't accept precedding spaces. e.g. " 101":
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <exception>
long strict_conversion(const std::string& number_string)
{
long number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}
After one minute, here is the generic one:
template <typename NumberType>
NumberType strict_conversion(const std::string& number_string)
{
NumberType number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}
|
3,065,836 | 3,065,875 | Operator & and * at function prototype in class | I'm having a problem with a class like this:
class Sprite {
...
bool checkCollision(Sprite &spr);
...
};
So, if I have that class, I can do this:
ball.checkCollision(bar1);
But if I change the class to this:
class Sprite {
...
bool checkCollision(Sprite* spr);
...
};
I have to do this:
ball.checkCollision(&bar1);
So, what's the difference?? It's better a way instead other?
Thank you.
| In both cases you are actually passing the address of bar1 (and you're not copying the value), since both pointers (Sprite *) and references (Sprite &) have reference semantics, in the first case explicit (you have to explicitly dereference the pointer to manipulate the pointed object, and you have to explicitly pass the address of the object to a pointer parameter), in the second case implicit (when you manipulate a reference it's as if you're manipulating the object itself, so they have value syntax, and the caller's code doesn't explicitly pass a pointer using the & operator).
So, the big difference between pointers and references is on what you can do on the pointer/reference variable: pointer variables themselves can be modified, so they may be changed to point to something else, can be NULLed, incremented, decremented, etc, so there's a strong separation between activities on the pointer (that you access directly with the variable name) and on the object that it points to (that you access with the * operator - or, if you want to access to the members, with the -> shortcut).
References, instead, aim to be just an alias to the object they point to, and do not allow changes to the reference itself: you initialize them with the object they refer to, and then they act as if they were such object for their whole life.
In general, in C++ references are preferred over pointers, for the motivations I said and for some other that you can find in the appropriate section of C++ FAQ.
In terms of performance, they should be the same, because a reference is actually a pointer in disguise; still, there may be some corner case in which the compiler may optimize more when the code uses a reference instead of a pointer, because references are guaranteed not to change the address they hide (i.e., from the beginning to the end of their life they always point to the same object), so in some strange case you may gain something in performance using references, but, again, the point of using references is about good programming style and readability, not performance.
|
3,065,903 | 3,066,008 | Issue with class template partial specialization | I've been trying to implement a function that needs partial template specializations and fallen back to the static struct technique, and I'm having a number of problems.
template<typename T> struct PushImpl<const T&> {
typedef T* result_type;
typedef const T& argument_type;
template<int StackSize> static result_type Push(IStack<StackSize>* sptr, argument_type ref) {
// Code if the template is T&
}
};
template<typename T> struct PushImpl<const T*> {
typedef T* result_type;
typedef const T* argument_type;
template<int StackSize> static result_type Push(IStack<StackSize>* sptr, argument_type ptr) {
return PushImpl<const T&>::Push(sptr, *ptr);
}
};
template<typename T> struct PushImpl {
typedef T* result_type;
typedef const T& argument_type;
template<int StackSize> static result_type Push(IStack<StackSize>* sptr, argument_type ref) {
// Code if the template is neither T* nor T&
}
};
template<typename T> typename PushImpl<T>::result_type Push(typename PushImpl<T>::argument_type ref) {
return PushImpl<T>::Push(this, ref);
}
First: The struct is nested inside another class (the one that offers Push as a member func), but it can't access the template parameter (StackSize), even though my other nested classes all could. I've worked around it, but it would be cleaner if they could just access StackSize like a normal class.
Second: The compiler complains that it doesn't use or can't deduce T. Really?
Thirdly: The compiler complains that it can't specialize a template in the current scope (class scope).
I can't see what the problem is. Have I accidentally invoked some bad syntax?
| The general case must appear before the specializations, otherwise the specializations have nothing to specialize.
|
3,065,948 | 3,065,980 | C++ Unions bit fields task | Can somebody clear me out why would I use union and with what purpose the same address for the cin'ed variable and bit field (task from the Schildts C++ book)? In other words why would I use union for :
char ch;
struct byte bit;
// Display the ASCII code in binary for characters.
#include <iostream>
#include <conio.h>
using namespace std;
// a bit field that will be decoded
struct byte {
unsigned a : 1;
unsigned b : 1;
unsigned c : 1;
unsigned d : 1;
unsigned e : 1;
unsigned f : 1;
unsigned g : 1;
unsigned h : 1;
};
union bits {
char ch;
struct byte bit;
} ascii ;
void disp_bits(bits b);
int main()
{
do {
cin >> ascii.ch;
cout << ": ";
disp_bits(ascii);
} while(ascii.ch!='q'); // quit if q typed
return 0;
}
// Display the bit pattern for each character.
void disp_bits(bits b)
{
if(b.bit.h) cout << "1 ";
else cout << "0 ";
if(b.bit.g) cout << "1 ";
else cout << "0 ";
if(b.bit.f) cout << "1 ";
else cout << "0 ";
if(b.bit.e) cout << "1 ";
else cout << "0 ";
if(b.bit.d) cout << "1 ";
else cout << "0 ";
if(b.bit.c) cout << "1 ";
else cout << "0 ";
if(b.bit.b) cout << "1 ";
else cout << "0 ";
if(b.bit.a) cout << "1 ";
else cout << "0 ";
cout << "\n";
}
| As a union, both ch and bit have an overlapped (shared) memory location. Store a character in it as ch and then reading bit produces the corresponding bit values for the character.
|
3,066,082 | 3,066,094 | How to keep my topmost window on top? | I will first explain why I need it, because I anticipate that the first response will be "Why do you need it?". I want to detect when the mouse cursor is on an edge of the screen and I don't want to use hooks. Hence, I created one pixel wide TOPMOST invisible window.
I am using C++ on Win XP, so when the window is created (CreateWindowEx(WS_EX_TOPMOST | WS_EX_TRANSPARENT ...) everything works fine.
Unfortunately, if a user moves another topmost window, for example the taskbar over my window, I don't get mouse movements.
I tried to solve this similarly to approaches suggested in:
How To Keep an MDI Window Always on Top
I tried to check for Z-order of my topmost window in WM_WINDOWPOSCHANGED first with
case WM_WINDOWPOSCHANGED :
WINDOWPOS* pWP = (WINDOWPOS*)lParam;
yet pWP->hwnd points to my window and pWP->hwndInsertAfter is 0, which should mean that my window is on the top of the Z, even though it is covered with the taskbar. Then I tried:
case WM_WINDOWPOSCHANGED :
HWND topWndHndl = GetNextWindow(myHandle, GW_HWNDPREV)
GetWindowText(topWndHndl, pszMem, cTxtLen + 1);
and I'll always get that the "Default IME" window is on top of my window. Even if try to bring my window to the top with SetWindowPos() or BringWindowToTop (), "Default IME" stays on the top. I don't know what is "Default IME" and how to detect if the taskbar is on top of my window.
So my question is: How to detect that my topmost window is not the top topmost window anymore and how to keep it on the top?
P.S. I know that a "brute force" approach of periodically bringing my window to the top works, yet is ugly and could have some unwanted inference with the notification window for example. (Bringing my window to the top will hide the notification window.)
Thank you on your time and suggestions!
| TopMost, is always a tricky thing. There is no way to override another window that specifies itself as TopMost.
Raymond Chen has a good article on this.
Also a duplicate of this.
|
3,066,191 | 3,066,223 | C++ Static Array Initialization - Memory Issue | I have a header file which contains a member variable declaration of a static char array:
class ABC
{
public:
static char newArray[4];
// other variables / functions
private:
void setArray(int i, char * ptr);
}
In the CPP file, I have the array initialized to NULL:
char ABC::newArray[4] = {0};
In the ABC constructor, I need to overwrite this value with a value constructed at runtime, such as the encoding of an integer:
ABC::ABC()
{
int i; //some int value defined at runtime
memset(newArray, 0, 4); // not sure if this is necessary
setArray(i,newArray);
}
...
void setArray(int i, char * value)
{
// encoding i to set value[0] ... value [3]
}
When I return from this function, and print the modified newArray value, it prints out many more characters than the 4 specified in the array declaration.
Any ideas why this is the case.
I just want to set the char array to 4 characters and nothing further.
Thanks...
| How are you printing it? In C++ (and C), strings are terminated with a nul. (\0). If you're doing something like:
char arr[4] = {'u', 'h', 'o', 'h'};
std::cout << arr;
It's going to print "uhoh" along with anything else it runs across until it gets to a \0. You might want to do something like:
for (unsigned i = 0; i < 4; ++i)
std::cout << arr[i];
(Having a static tied to instances of a class doesn't really make sense, by the way. Also, you can just do = {}, though it's not needed since static variables are zero-initialized anyway. Lastly, no it doesn't make sense to memset something then rewrite the contents anyway.)
|
3,066,192 | 3,066,226 | AVG Access Denied warning when running the simplest C++ program | I am running a very simple C++ program:
#include <list>
#include <vector>
int main(int argc, char **args) {
}
I go to the command prompt and compile and run:
g++ whatever.cpp
a.exe
Normally this works just fine. It compiles fine, but when I run it it says Access Denied and AVG pops up telling me that a threat has been detected Trojan Horse Generic 17.CKZT. I tried compiling again using the Microsoft Compiler (cl.exe) and it runs fines. So I went back, and added:
#include <iostream>
compiled using g++ and ran. This time it worked fine.
So can anyone tell me why AVG would report an empty main method as a trojan horse but if the iostream header is included it doesn't?
UPDATE:
I added a return statement to the main method and now I find that I only get the error if I return 0. Any other return value and it seems to work fine.
What's going on here?
| You're not the first person to encounter false positives by antivirus software.
What probably happened is that the antivirus heuristics tripped up on the standard runtime libraries present in your programs, since malware uses them as well. Of course, legitimate software uses them too! The fact that it didn't trip up on iostream probably means that iostream isn't very popular among malware writers.
|
3,066,557 | 3,066,812 | Exception handling in Boost.Asio | Boost.Asio documentation suggests the following exception handling pattern:
boost::asio::io_service io_service;
...
for (;;)
{
try
{
io_service.run();
break; // run() exited normally
}
catch (my_exception& e)
{
// Deal with exception as appropriate.
}
}
The problem with it is that the context of exception is lost at the point when it's handled. For example, if I have multiple socket sessions in a given io_service, I don't know which one caused the exception.
What would be a better way to handle the exceptions from asynchronous handlers without wrapping them in try/catch blocks?
| There is nothing wrong with the pattern recommended by Boost.Asio. What you should do is package any necessary information for handling the exception along with the exception object. If you use boost::exception (or a type derived from it) for your exception handling, you can very easily attach metadata (including session information) by creating a specialization of boost::error_info and attaching it to the exception object using operator<<. Your catch block can then extract this info with get_error_info.
|
3,066,566 | 3,069,578 | Attempt to open browser in C++ | I am attempting to open Firefox using C++ on Linux (Ubuntu). However, I get an segmentation fault. What am I doing wrong, and what should I do?
std::cout << system("/usr/bin/firefox") << std::endl;
| To answer my own question:
It works fine, as posted a few times above. The problem was that I was using Netbeans. Netbeans caused a Segmentation Fault when trying to run it. Running outside Netbeans gave the expected result.
Nothing wrong with the code, just with Netbeans, strangely enough.
So everyone with the same error, try run it outside Netbeans.
|
3,066,621 | 3,068,326 | C++ Segmentation fault in binary_function | I'm using Visual Studio 2010 Beta 2 (also tried with NetBeans), and I'm having a segmentation fault in the following code:
// One of the @link s20_3_3_comparisons comparison functors@endlink.
template <class _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; } //this is the problem line
};
I don't know what in my program calls it, but I am trying to find out. (I think it's a map) Does anyone know what to do, or has encountered this before?
| I had the same problem yesterday.
This is tried and tested code so there is a very low probability this is causing the crash.
Usually there are three possibilities for this crash:
another problem is causing a corruption of the data that this function is called on
another problem is causing a corruption of your stack causing this function to be called when it shouldn't be
any combination of the two possibilities above.
To diagnose this, run your code in the VS debugger. When your application crashes, look at the parameter values and check that the stack trace shown in the debugger is the same as the stack trace you should see (click on each entry in the stack trace and look and see the code is calling what it should).
|
3,066,635 | 3,076,281 | Finding the intersection of two vector equations | I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing:
v1 = (a,b)
v2 = (c,d)
d1 = (e,f)
d2 = (h,i)
l1: v1 + λd1
l2: v2 + µd2
Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda.
(a,b) + λ(e,f) = (c,d) + µ(h,i)
a + λe = c + µh
b +λf = d + µi
µh = a + λe - c
µi = b +λf - d
µ = (a + λe - c)/h
µ = (b +λf - d)/i
(a + λe - c)/h = (b +λf - d)/i
a/h + λe/h - c/h = b/i +λf/i - d/i
λe/h - λf/i = (b/i - d/i) - (a/h - c/h)
λ(e/h - f/i) = (b - d)/i - (a - c)/h
λ = ((b - d)/i - (a - c)/h)/(e/h - f/i)
Intersection vector = (a + λe,b + λf)
Not sure if it would even work in some cases. I haven't tested it.
I need to know how to do this for values as in that example a-i.
Thank you.
| Here's the solution with a python function. v1 and v2 are the position vectors. d1 and d2 are the direction vectors.
def vector_intersection(v1,v2,d1,d2):
'''
v1 and v2 - Vector points
d1 and d2 - Direction vectors
returns the intersection point for the two vector line equations.
'''
if d1[0] == 0 and d2[0] != 0 or d1[1] == 0 and d2[1] != 0:
if d1[0] == 0 and d2[0] != 0:
mu = float(v1[0] - v2[0])/d2[0]
elif d1[1] == 0 and d2[1] != 0:
mu = float(v1[1] - v2[1])/d2[1]
return (v2[0] + mu* d2[0],v2[1] + mu * d2[1])
else:
if d1[0] != 0 and d1[1] != 0 and d2[0] != 0 and d2[1] != 0:
if d1[1]*d2[0] - d1[0]*d2[1] == 0:
raise ValueError('Direction vectors are invalid. (Parallel)')
lmbda = float(v1[0]*d2[1] - v1[1]*d2[0] - v2[0]*d2[1] + v2[1]*d2[0])/(d1[1]*d2[0] - d1[0]*d2[1])
elif d2[0] == 0 and d1[0] != 0:
lmbda = float(v2[0] - v1[0])/d1[0]
elif d2[1] == 0 and d1[1] != 0:
lmbda = float(v2[1] - v1[1])/d1[1]
else:
raise ValueError('Direction vectors are invalid.')
return (v1[0] + lmbda* d1[0],v1[1] + lmbda * d1[1])
|
3,066,728 | 3,066,849 | Problem with variable argument function in C++ | I'm trying to create a variable length function (obviously, heh) in C++, and what I have right now works, but only for the first argument. If someone could please let me know how to get this working with all the arguments that are passed, I would really appreciate it.
Code:
void udStaticObject::accept( udObjectVisitor *visitor, ... )
{
va_list marker;
udObjectVisitor *i = visitor;
va_start( marker, visitor );
while( 1 )
{
i->visit_staticObject( this );
//the if here will always go to the break immediately, allowing only
//one argument to be used
if( ( i = va_arg( marker, udObjectVisitor* ) ) )
break;
}
va_end( marker );
}
Based on my past posts, and any help posts I make in general, there is probably some information that I did not provide that you will need to know to help. I apologize in advance if I forgot anything, and please let me know what you need to know so I can provide the information.
| If you use a variadic function, you need some way to tell the function how many arguments were passed. For example, printf() and friends take a formatting string that contains format specifiers for each of the passed arguments, and they count the number of format specifiers to determine how many arguments were passed.
When passing a list of pointers, you can accomplish this "more simply" by passing a null pointer as the last argument. That way, you simply read arguments until you reach the null pointer.
However, you should seriously consider not using a variadic function for this. You can accomplish the same behavior by taking a vector of pointers as a parameter and iterating over the contents of that vector. There are a number of reasons why this is superior to using a variadic function:
Variadic functions have absolutely no type safety. You lose any and all type information about the arguments when you pass them to a variadic function, so for example, a caller of your function could pass a numeric value instead of a pointer and you'd never be able to tell inside of your function.
With the variadic solution, the caller must correctly indicate the number of arguments. If the caller omits the null pointer at the end (or otherwise misinforms your function of how many arguments there are) and you try to read more arguments than were passed, you end up with undefined behavior. Right now you might say "well, that's not hard to forget," but inevitably, someone will forget or screw it up and debugging this sort of issue is a beating.
The solution taking a vector and iterating over its contents is far simpler to implement, easier to debug, and much more idiomatic in C++.
Wherever there is an option between using a variadic function and not using a variadic function, you should prefer not to use a variadic function (I'll admit, I have never written a variadic function in any of the C++ code I have written, though I've written a few in C).
|
3,066,863 | 3,066,874 | What's the difference between a const member function and a non-const member function? | I am very confused about the const version and non-const version member function like below:
value_type& top() { return this.item }
const value_type& top() const { return this.item }
What is the difference between these two functions? In what situation would they be used?
| In short, they're used to add 'const correctness' to your program.
value_type& top() { return this.item }
This is used to provide mutable access to item. It is used so you can modify the element in the container.
For example:
c.top().set_property(5); // OK - sets a property of 'item'
cout << c.top().get_property(); // OK - gets a property of 'item'
One common example for this pattern is returning mutable access to an element with vector::operator[int index].
std::vector<int> v(5);
v[0] = 1; // Returns operator[] returns int&.
On the other hand:
const value_type& top() const { return this.item }
This is used to provide const access to item. It's more restrictive than the previous version - but it has one advantage - you can call it on a const object.
void Foo(const Container &c) {
c.top(); // Since 'c' is const, you cannot modify it... so the const top is called.
c.top().set_property(5); // compile error can't modify const 'item'.
c.top().get_property(); // OK, const access on 'item'.
}
To follow the vector example:
const std::vector<int> v(5, 2);
v[0] = 5; // compile error, can't mutate a const vector.
std::cout << v[1]; // OK, const access to the vector.
|
3,067,235 | 3,067,361 | SDL_ttf and Numbers (int) | int score = 0;
char* fixedscore=(char*)score;
.
.
.
imgTxt = TTF_RenderText_Solid( font, fixedscore, fColor );
^^ This doesn't work - looks like fixedscore is empty or doesn't exists.
int score = 0;
char* fixedscore=(char*)score;
.
.
.
imgTxt = TTF_RenderText_Solid( font, "Works fine", fColor );
^^ Works fine, but...
I guess converting int to char* doesn't really work. So how do you print scores in SDL?
Oh and one more thing: why is the text so ugly?
| Casting is not what you want. This code:
int score = 0;
char* fixedscore=(char*)score;
is the equivalent of doing:
char* fixedscore = NULL;
I assume you are trying to get fixedscore to hold the textual value of the number in score. The easiest way using just standard C++ is via stringstream:
std::stringstream strm;
strm << score;
...
imgTxt = TTF_RenderText_Solid( font, strm.str().c_str(), fColor );
|
3,067,330 | 3,067,336 | pass by pointer is not working | #include"iostream"
class CMessage
{
public:int a;
CMessage(){}
~CMessage(){}
};
void Testing(CMessage *f_pMessage)//l_pMessage is output parameter
{
f_pMessage = new CMessage();
f_pMessage->a = 1;
}
int main()
{
CMessage *l_pMessage =NULL;
Testing(l_pMessage);
std::cout<<l_pMessage->a;//getting l_pMessage = NULL;
return 0;
}
When I called testing then inside testing f_pMessage is getting initialized but as soon as
i after excuting testing function it should be store in l_Pmessage but it is showing NULL.confussed.....
| Passing by pointer only allows you to modify what is being pointed at. The pointer itself is still being passed by value.
Since you want to change a pointer, you can either pass a pointer to a pointer or take the pointer by reference:
void Testing(CMessage *&f_pMessage)//l_pMessage is output parameter
{
f_pMessage = new CMessage();
f_pMessage->a = 1;
}
|
3,067,816 | 3,068,050 | Can't build full html table in QTextEdit with std::for_each | Here is my code function:
void ReportHistory::update(void)
{
ui.output->clear();
ui.output->setCurrentFont(QFont("Arial", 8, QFont::Normal));
QString title = "My Title";
QStringList headers = QString("Header1,Header2,Header3,Header4,Header5,Header6").split(",");
QString html = QString(
"<html>" \
"<head>" \
"<meta Content=\"Text/html; charset=Windows-1251\">" \
"<title>%1</title>" \
"</head>" \
"<body bgcolor=#ffffff link=#5000A0>" \
"<p>%1</p>" \
"<table border=1 cellspacing=0 cellpadding=2>" \
"<tr bgcolor=#f0f0f0>"
).arg(title);
foreach (QString header, headers)
{
html.append(QString("<th>%1</th>").arg(header));
}
html.append("</tr>");
struct Fill
{
QString html_;
Analytics::NavHistory::History::value_type prev_;
Fill(QString html) : html_(html)
{}
void operator ()(const Analytics::NavHistory::History::value_type& entry)
{
QStringList line = (QString(
"%1|%2|%3|%4|%5|%6"
).arg(value1, 15)
.arg(value2 ? ' ' : 'C', 8)
.arg(value3, 15)
.arg(value4, 15, 'f', 4)
.arg(value5, 15)
.arg(value6, 15, 'f', 4)).split("|");
html_.append("<tr>");
foreach (QString item, line)
{
html_.append("<td bkcolor=0>%1</td>").arg(item);
}
html_.append("</tr>");
prev_ = entry;
}
};
std::for_each(history_->data().begin(), history_->data().end(), Fill(html));
html.append(
"</table>" \
"</body>" \
"</html>");
ui.output->setHtml(html);
}
Where:
ui.output is a pointer to QTextEdit.
Question: the ui.output just show me the headers, and not the full table, what is wrong?
Thanks.
| You are taking a copy of the QString in your functor and so the original is never modified. Try changing it to
struct Fill
{
QString& html_;
Analytics::NavHistory::History::value_type prev_;
Fill(QString& html) : html_(html)
{}
// etc...
};
and it should work.
|
3,067,892 | 3,067,933 | Can I catch bad pointer errors in C++? | I was wondering if there is a possibility to catch errors like this in C++:
object* p = new object;
delete p;
delete p; // This would cause an error, can I catch this?
Can I check if the pointer is valid?
Can I catch some exception?
I know I could set the pointer p to NULL after the first object deletion. But just imagine you wouldn't do that.
| I don't think you can catch this kind of error because I think the result is undefined behaviour. It might do nothing, it might crash, it might just corrupt the memory and cause a problem later down the line.
If you found it did something specific with your current compiler you could try and handle that, but it might do different things in debug and release, and different again when you upgrade the compiler version.
Setting the pointer to null has been suggested, but I think you would be better off using smart pointers and not deleting them at all.
|
3,067,998 | 3,068,059 | How to marshall data type unsigned char** in C#? | I'm trying to marshall unsigned char** (which is in a C++ interface) in order to call the method from C#.
How can this be done? Is there a list where are C++ data types and C# data types?
Thanks!
| What is the semantics of this unsigned char**? If it is a byte array, use ref byte[].
If it is a zero terminated string, use ref string.
You can find some popular method signatures mapped to c# on the page http://www.pinvoke.net, which may give you the idea.
|
3,068,088 | 3,068,141 | How to write INT64 to CString | I am coding in c++ windows.
INT64 dirID = -1;
CString querySQLStr = _T("");
querySQLStr.Format(L"select * from ImageInfo where FolderPath=%64d;", dirID);
querySQLStr always like this:
select * from ImageInfo where FolderPath= 1214;
is it right to use %64d?
Many Thanks
| I don't have a windows machine handy to test this on, but I think CString should accept this:
querySQLStr.Format("%I64d", dirID);
It's probably worth noting that this is windows specific, but since you're using CString I guess that's okay.
|
3,068,144 | 12,187,582 | Print address of virtual member function | I am trying to print the address of a virtual member function.
If I know which class implements the function I can write:
print("address: %p", &A::func);
But I want to do something like this:
A *b = new B();
printf("address: %p", &b->func);
printf("address: %p", &b->A::func);
However this does not compile. Is it possible to do something like this, perhaps looking up the address in the vtable at runtime?
| Currently there is no standard way of doing this in C++ although the information must be available somewhere. Otherwise, how could the program call the function? However, GCC provides an extension that allows us to retrieve the address of a virtual function:
void (A::*mfp)() = &A::func;
printf("address: %p", (void*)(b->*mfp));
...assuming the member function has the prototype void func().
This can be pretty useful when you want to cache the address of a virtual function or use it in generated code. GCC will warn you about this construct unless you specify -Wno-pmf-conversions. It's unlikely that it works with any other compiler.
|
3,068,198 | 3,073,626 | How to read a multiple line input from command line in c or C++? | For Example:
If I need to read a multiple line input like(and I dont know How many lines would be there!!):
1 20
2 31
3 41
I am using something like
int main()
{
string line;
while(getline(cin,line) != NULL)
{
// some code
// some code
}
}
Now the program never stops- i.e always it expects some input. How do i beak the loop when there are no more input lines ?
| Just test the variable line for empty each time you read a line. If the use presses enter with no other data, then line will be empty.
#include <iostream>
#include <string>
using std::cin;
using std::getline;
using std::string;
int main(int argc, char *argv[]) {
string line;
while (true) {
getline(cin, line);
if (line.empty()) {
break;
}
// some code
}
return 0;
}
|
3,068,231 | 3,122,668 | IPV6 link local multicasting | I'm trying to figure out how to do the equivalent of an IPV4 broadcast using IPV6.
I'm creating a non-blocking IPV6 UDP socket.
From the side broadcasting i'm literally just doing a sendto "FF02::1" on port 12346.
On the listen side I discovered I need to join the group so I did the following:
ipv6_mreq membership;
memset( &membership.ipv6mr_multiaddr, 0, sizeof( in6_addr ) );
membership.ipv6mr_multiaddr.u.Word[0] = htons( 0xff02 );
membership.ipv6mr_multiaddr.u.Word[7] = htons( 0x0001 );
membership.ipv6mr_interface = 0;
if( enable )
{
if ( 0 != setsockopt( m_Socket, SOL_SOCKET, IPV6_JOIN_GROUP, (char*)&membership, sizeof( ipv6_mreq ) ) )
{
DisplayError();
return false;
}
}
However setsockopt always returns "WSAENOPROTOOPT". Why? Can anyone help me on this one? I'm at a complete loss.
Edit: I change the level to "IPPROTO_IPV6" but now I get a "WSAEINVAL".
| The interface must be set for locally scoped IPv6 because the addresses are only unique to the interface. In simpler terms the address fe80::1 can belong to both eth0 and eth1 but are completely separate.
So this means you need to explicitly send a multicast packet on every up interface that supports multicast, or provide the user with a means of specifying a particular interface.
(edit) If it helps you can check out multicast code here,
http://code.google.com/p/openpgm/source/browse/trunk/openpgm/pgm/
|
3,068,454 | 3,068,584 | Can I have managed code within native code? | Can I have managed code within native code?
| There are quite a few ways to do this.
You can code in C++/CLI, the managed C++ compiler provided by Microsoft. You can mix managed and native code as you wish (security restrictions may apply).
You can go the COM route, and it's natively supported on the .NET side. Harder to program on the native side though, especially all the interop. You can start here: http://msdn.microsoft.com/en-us/magazine/cc163494.aspx.
The 3rd way is to "host" the .net runtime engine directly into your app and use it to load managed assemblies and then execute parts from them. This may be overkill for you, but it generates a 100% native image and doesn't rely on COM interop. You can start here: http://msdn.microsoft.com/en-us/library/dd380850.aspx.
|
3,068,513 | 3,068,535 | How can I avoid repeating code with inline functions? | I have repeating code in my work, and I want to get rid of it, so I know that in C++ it is not good idea to use macro, but instead I must use inline function, is it good idea to use this function as inline:
list<Data>::iterator foo(int data){
if(dataExists(data)){
list<Data>::iterator i;
for(i = dataClass.begin(); i != dataClass.end(); ++i){
if(i->getData() == data){
break;
}
return i; //here I have one more problem, what can I return if data doesn't exist?
}
I think that this function is very unsafe. How can I improve my code?
| What you're doing here is already done by the std::find() function, so it would be better to use that (although it's certainly OK to try implementing these things yourself for the exercise).
std::find() also demonstrates a good way to indicate the "not found" condition -- if the item is not found, it returns the iterator one-past-the-end. That way, the caller can determine whether a matching item was found by comparing the iterator returned with Data.end().
|
3,068,562 | 21,745,254 | Accessing typedef from the instance | As in stl containers, why can't we access a typedef inside the class from the class instance? Is there a particular insight into this?
When value_type was a template parameter it could help making more general code if there wasn't the need to specify the template parameters as in vector::value_type
Example:
class T {
public:
typedef int value_type;
value_type i;
};
T t;
T::value_type i; // ok
t.value_type i; // won't work
| The answer is use decltype to get the class first. E.g.,
decltype(t)::value_type
Requires C++11.
Reference: https://stackoverflow.com/a/13936644/577704
|
3,068,955 | 3,069,038 | Inheritance and choose constructor from base class | My question is rather simple, but I am stuck. How can I choose the desired constructor from base class?
// node.h
#ifndef NODE_H
#define NODE_H
#include <vector>
// definition of an exception-class
class WrongBoundsException
{
};
class Node
{
public:
...
Node(double, double, std::vector<double>&) throw (WrongBoundsException);
...
};
#endif
// InternalNode.h
#ifndef INTERNALNODE_H
#define INTERNALNODE_H
#include <vector>
#include "Node.h"
class InternalNode : public Node
{
public:
// the position of the leftmost child (child left)
int left_child;
// the position of the parent
int parent;
InternalNode(double, double, std::vector<double>&, int parent, int left_child) throw (WrongBoundsException);
private:
int abcd;
};
#endif
// InternalNode.cpp
#include "InternalNode.h"
#define UNDEFINED_CHILD -1
#define ROOT -1
// Here is the problem
InternalNode::InternalNode(double a, double b, std::vector<double> &v, int par, int lc)
throw (WrongBoundsException)
: Node(a, b, v), parent(par), left_child(lc)
{
std::cout << par << std::endl;
}
I get:
$ g++ InternalNode.cpp
InternalNode.cpp:16: error: declaration of ‘InternalNode::InternalNode(double, double, std::vector >&, int, int) throw (WrongBoundsException)’ throws different exceptions
InternalNode.h:17: error: from previous declaration ‘InternalNode::InternalNode(double, double, std::vector >&, int, int)’
UPDATE 0: Fixed missing :
UPDATE 1: Fixed throw exception
| This simplified code compiles correctly, but doesn't link becuase of missing constructor definition for base class:
#include <vector>
// definition of an exception-class
class WrongBoundsException {
};
class Node {
public:
Node(double, double, std::vector<double>&)
throw (WrongBoundsException);
};
class InternalNode : public Node {
public:
// the position of the leftmost child (child left)
int left_child;
// the position of the parent
int parent;
InternalNode(double, double, std::vector<double>&,
int parent, int left_child)
throw (WrongBoundsException);
private:
int abcd;
};
// Note added exception specification
InternalNode::InternalNode(double a, double b,
std::vector<double> &v,
int par, int lc) throw (WrongBoundsException)
: Node(a, b, v), parent(par), left_child(lc)
{
}
BTW, why do you feel the need to use exception specifications? They are generally seem as a bit of a waste of time in C++.
|
3,069,082 | 3,070,258 | Porting getifaddrs to Win XP | I'm trying to port a MacOSX app to windows and I've come up against a problem around getifaddrs. Basically windows does not support it. I'm trying to figure a way to re-implement it (for AF_INET and AF_INET6) but the "equivalent" functionality on windows appears to be nothing like the MacOSX support.
Has someone done this sort of conversion before? If so is there a nice way I can get windows to report me interface info like MacOSX does?
| The closest functions on Windows are GetAdaptersInfo and GetAdaptersAddresses. The MSDN documentation is pretty comprehensive, so you should find everything you need.
|
3,069,123 | 3,069,980 | Odd C++ template behaviour with static member vars | This piece of code is supposed to calculate an approximation to e (i.e. the mathematical constant ~ 2.71828183) at compile-time, using the following approach;
e1 = 2 / 1
e2 = (2 * 2 + 1) / (2 * 1) = 5 / 2 = 2.5
e3 = (3 * 5 + 1) / (3 * 2) = 16 / 6 ~ 2.67
e4 = (4 * 16 + 1) / (4 * 6) = 65 / 24 ~ 2.708
...
e(i) = (e(i-1).numer * i + 1) / (e(i-1).denom * i)
The computation is returned via the result static member however, after 2 iterations it yields zero instead of the expected value. I've added a static member function f() to compute the same value and that doesn't exhibit the same problem.
#include <iostream>
#include <iomanip>
// Recursive case.
template<int Iters, int Num = 2, int Den = 1, int I = 2>
struct CalcE
{
static const double result;
static double f () {return CalcE<Iters, Num * I + 1, Den * I, I + 1>::f ();}
};
template<int Iters, int Num, int Den, int I>
const double CalcE<Iters, Num, Den, I>::result = CalcE<Iters, Num * I + 1, Den * I, I + 1>::result;
// Base case.
template<int Iters, int Num, int Den>
struct CalcE<Iters, Num, Den, Iters>
{
static const double result;
static double f () {return result;}
};
template<int Iters, int Num, int Den>
const double CalcE<Iters, Num, Den, Iters>::result = static_cast<double>(Num) / Den;
// Test it.
int main (int argc, char* argv[])
{
std::cout << std::setprecision (8);
std::cout << "e2 ~ " << CalcE<2>::result << std::endl;
std::cout << "e3 ~ " << CalcE<3>::result << std::endl;
std::cout << "e4 ~ " << CalcE<4>::result << std::endl;
std::cout << "e5 ~ " << CalcE<5>::result << std::endl;
std::cout << std::endl;
std::cout << "e2 ~ " << CalcE<2>::f () << std::endl;
std::cout << "e3 ~ " << CalcE<3>::f () << std::endl;
std::cout << "e4 ~ " << CalcE<4>::f () << std::endl;
std::cout << "e5 ~ " << CalcE<5>::f () << std::endl;
return 0;
}
I've tested this with VS 2008 and VS 2010, and get the same results in each case:
e2 ~ 2
e3 ~ 2.5
e4 ~ 0
e5 ~ 0
e2 ~ 2
e3 ~ 2.5
e4 ~ 2.6666667
e5 ~ 2.7083333
Why does result not yield the expected values whereas f() does?
According to Rotsor's comment below, this does work with GCC, so I guess the question is, am i relying on some type of undefined behaviour with regards to static initialisation order, or is this a bug with Visual Studio?
| Apparently you can't depend on the order of static member initialization, at least in VC++.
Here's a simplified example:
#include <stdio.h>
template<int N>
struct one
{
static const int res;
};
template<>
struct one<0>
{
static const int res;
};
template<int N>
const int one<N>::res = one<N-1>::res;
const int one<0>::res = 1;
int main()
{
printf("%d\n", one<3>::res);
printf("%d\n", one<2>::res);
printf("%d\n", one<1>::res);
printf("%d\n", one<0>::res);
}
In VC++ 2008, it produces:
0
1
1
1
In codepad, it produces:
1
1
1
1
|
3,069,182 | 3,069,230 | How can I see the C/C++ #include graph easily? | I'm looking for a tool (preferably, a Visual Studio plugin) that would display all files included by a given file and show all files included by those files and so on.
| Doxygen, with the aid of Graphviz, can do that. You first need to edit a configuration file. This won't be easy the first time you do it, but no much editing is needed afterwards.
|
3,069,200 | 3,069,220 | String::New: what is it? | I am from a Java background and is learning C++. I encountered the following C++ code:
String source = String::New("'Hello' + ', World'");
As what I understand so far, this should be a call to static member function 'New' of class 'String'. But, I've searched through the whole header file defining 'String', there is not any static member named 'New' in the String class or its super classes. Is there any special meaning attached to String class or the New member function in C++?
| You are correct. That is calling the static method New on the String class.
C++ (or STL) doesn't have a native String class, there is a string class, but it doesn't have a ::New method. You'll have to make sure you're reading the right documentation :)
It's possible that it's inherited from a base-class, so make sure you check if String is part of an inheritance hierarchy.
Here's the deal with v8's String. It's interesting.
There are two implementations:
v8::String - the externally visible one (Here is doxygen documentation showing the class hierarchy).
v8::internal::String - the internal representation.
Browsing the internal String source code, String is indeed a heap allocated object representing a Javascript string.
It turns out that Google Code's UI is broken (maybe they have a maximum character count?). The v8::internal::HeapObject source code should be in src/objects.h, but the file is truncated. And the externally visible v8::String source code should be in include/v8.h, but it too is truncated.
You can download the source and view the files. Here is what it says:
/**
* A JavaScript string value (ECMA-262, 4.3.17).
*/
class V8EXPORT String : public Primitive {
public:
...
/**
* Allocates a new string from either utf-8 encoded or ascii data.
* The second parameter 'length' gives the buffer length.
* If the data is utf-8 encoded, the caller must
* be careful to supply the length parameter.
* If it is not given, the function calls
* 'strlen' to determine the buffer length, it might be
* wrong if 'data' contains a null character.
*/
static Local<String> New(const char* data, int length = -1);
/** Allocates a new string from utf16 data.*/
static Local<String> New(const uint16_t* data, int length = -1);
...
};
|
3,069,208 | 3,069,949 | Converting IplImage into 1D vector in OpenCV | I want to convert a mXn IplImage into a (m*n) x 1 1D vector. Can this be done with any function in OpenCV?
Any help is greatly appreciated.
| cvReshape
CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn,
int newRows=0)
Changes shape of matrix/image without copying data.
And the next example converts a 3x3
matrix to a single 1x9 vector:
CvMat* mat = cvCreateMat(3, 3, CV_32F);
CvMat row_header, *row;
row = cvReshape(mat, &row_header, 0, 1);
|
3,069,255 | 3,069,281 | Singleton & Multi-threading | I have the following class
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
Please do elaborate on precautions taken while implementing Singleton in multi-threaded environment .
| In multi-threading that clause
if(!p_inst)
{
p_inst = new Singleton();
}
is actually 3 separate actions. You are getting the value of p_inst, setting the value of p_inst and writing the value of p_inst. So get-set-write means that you need to put a lock around p_inst otherwise you can have 2 threads which create a Singleton value that each thread uses.
Here is how you can view the issue, assume that your Singleton has a mutable field val:
thread A -> p_inst is NULL
thread B -> p_inst is NULL
thread A -> set to Singleton (1)
thread B -> set to Singleton (2)
thread C -> p_inst is Singleton (2)
thread A -> set val to 4
thread B -> set val to 6
thread C -> get val (it's 6)
thread A -> get val (it's 4!!)
You see? There's 2 copies of a Singleton floating about, neither of which knows about the other. The third thread which checks on the Singleton is only going to see the last assignment. But with locking, you can prevent multiple assignment and these types of problems.
|
3,069,324 | 3,069,345 | New datatype which can have numbers upto 100 digits | Note: This was an interview question and may not have an actual use case currently
The question was to design a class that can store numbers which are very very large say each number can have 100 digits. This new class is a datatype like int.
What are the different types of constructors, overloads and other functions that you would write.
How can this be further extended to support really large floating point numbers.
How this can be given to others so that they can reuse the same component with their own additional functionality.
My answer consisted of 2 approaches
1. using array of integers to store every say 10 digits
2. using string itself to store the number and perform operations on individual numbers.
What would be the best approach?
| The best approach would be to propose they use am existing, tried and tested C++ wrapper for a bignum library like GMP.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.