question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,446,236 | 2,446,430 | C++ threaded class design from non-threaded class | I'm working on a library doing audio encoding/decoding. The encoder shall be able to use multiple cores (i.e. multiple threads, using boost library), if available. What i have right now is a class that performs all encoding-relevant operations.
The next step i want to take is to make that class threaded. So i'm wondering how to do this.
I thought about writing a thread-class, creating n threads for n cores and then calling the encoder with the appropriate arguments. But maybe this is an overkill and there is no need for another class, so i'm going to make use of the "user interface" for thread-creation.
I hope there are any suggestions.
Edit: I'm forced to use multiple threads for the pre-processing, creating statistics of the input data using CUDA. So, if there are multiple Cards in a system the only way to use them in parallel is to create multiple threads.
Example: 4 Files, 4 different calculation units (separate memories, unique device id). Each of the files shall be executed on one calculation unit.
What i have right now is:
class Encoder {
[...]
public:
worker(T data, int devId);
[...]
}
So i think the best way is to call worker from threaded from main()
boost::thread w1(&Encoder::worker, data0, 0);
boost::thread w2(&Encoder::worker, data1, 1);
boost::thread w3(&Encoder::worker, data2, 2);
boost::thread w4(&Encoder::worker, data3, 3);
and not to implement a thread-class.
| I think the problem is more at a design level, can you elaborate a bit on what classes do you have ? I work on CUDA too, and usually one creates an interface (aka Facade pattern) for using the architecture specific (CUDA) layer.
Edit: After reading the update interface I think you are doing the right thing.
Keep the Encoder logic inside the class and use plain boost::threads to execute different units of work. Just pay attention on thread safety inside Encoder's methods.
|
2,446,273 | 2,446,278 | Safely remove window subclassing? | I am trying to subclass the currently focused window on a Windows system using a global CBT hook. This is related to what happens in this question, but the bug is different.
What happens when this subclassing is in effect, is that Opera's (version 10.50) main window is prevented from displaying. Opera has a "splash screen" where you are required to click "Start" for the main window to show that appears after Opera has not shut down properly. Whenever this window pops up, Opera's main window won't show. If Opera was shut down properly, and this splash screen does not show, the main window displays as it should.
HHOOK hHook;
HWND hWndSubclass = 0;
void SubclassWindow(HWND hWnd)
{
Unsubclass();
FARPROC lpfnOldWndProc = (FARPROC)SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LPARAM)SubClassFunc);
SetProp(hWnd, L"PROP_OLDWNDPROC", lpfnOldWndProc);
hWndSubclass = hWnd;
}
void Unsubclass()
{
if (hWndSubclass != 0 && IsWindow(hWndSubclass))
{
FARPROC lpfnOldWndProc = (FARPROC)GetProp(hWndSubclass, L"PROP_OLDWNDPROC");
RemoveProp(hWndSubclass, L"PROP_OLDWNDPROC");
SetWindowLongPtr(hWndSubclass, GWLP_WNDPROC, (LPARAM)lpfnOldWndProc);
hWndSubclass = 0;
}
}
static LRESULT CALLBACK SubClassFunc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_MOVING)
{
// do something irrelevant
}
else if (message == WM_DESTROY)
{
Unsubclass();
}
FARPROC lpfnOldWndProc = (FARPROC)GetProp(hWndSubclass, L"PROP_OLDWNDPROC");
return CallWindowProc((WNDPROC)lpfnOldWndProc, hWndSubclass, message, wParam, lParam);
}
static LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HCBT_SETFOCUS && hWndServer != NULL)
{
SubclassWindow((HWND)wParam);
}
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
return 0;
}
BOOL APIENTRY DllMain( HINSTANCE hInstance,
DWORD Reason,
LPVOID Reserved
)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
hInst = hInstance;
return TRUE;
case DLL_PROCESS_DETACH:
Unsubclass();
return TRUE;
}
return TRUE;
}
My suspicion is that Opera's main window is somehow already subclassed. I imagine the following is happening:
The window is created with it's own basic WndProc, and is given focus
My application subclasses the window, storing the original WndProc
Opera subclasses its own window
When the window loses focus, I restore the original WndProc, thus ignoring the second WndProc
Can this really be the case? Are there any other explanations?
| This can happen, as Raymond Chen writes:
Consider what would happen if somebody else had subclassed the window during the "... do stuff ..." section. When we unsubclassed the window, we would have removed two subclasses, the one we installed, and the one that was installed after us. If the other subclass allocated memory (which is very common), then that memory got leaked, in addition to the subclass failing to do whatever it was trying to do.
He continues with a solution:
This is quite a cumbersome process, so the shell team wrote some helper functions to do all this for you. The SetWindowSubclass function does all the grunt work of installing a subclass procedure, remembering the previous one, and passing reference data to the subclass procedure you provide. You use the DefSubclassProc function to forward the message to the previous subclass procedure, and when you're done, you use the RemoveWindowSubclass function to remove yourself from the chain. RemoveWindowSubclass does all the work to do the right thing if you are not the window procerure at the top of the chain.
|
2,446,839 | 2,469,835 | Why I am getting a Heap Corruption Error? | I am new to C++. I am getting HEAP CORRUPTION ERROR. Any help will be highly appreciated. Below is my code
class CEntity
{
//some member variables
CEntity(string section1,string section2);
CEntity();
virtual ~CEntity();
//pure virtual function ..
virtual CEntity* create()const = 0;
};
I derive CLine from CEntity as below
class CLine:public CEntity
{
// Again some variables ...
// Constructor and destructor
CLine(string section1,string section2);
CLine();
~CLine();
CLine* Create() const;
}
// CLine Implementation
CLine::CLine(string section1,string section2) : CEntity(section1,section2){};
CLine::CLine();
CLine* CLine::create() const {return new CLine();}
I have another class CReader which uses CLine object and populates it in a multimap as below
class CReader
{
public:
CReader();
~CReader();
multimap<int,CEntity*>m_data_vs_entity;
};
//CReader Implementation
CReader::CReader()
{
m_data_vs_entity.clear();
};
CReader::~CReader()
{
multimap<int,CEntity*>::iterator iter;
for(iter = m_data_vs_entity.begin();iter!=m_data_vs_entity.end();iter++)
{
CEntity* current_entity = iter->second;
if(current_entity)
delete current_entity;
}
m_data_vs_entity.clear();
}
I am reading the data from a file and then populating the CLine Class.The map gets populated in a function of CReader class. Since CEntity has a virtual destructor, I hope the piece of code in CReader's destructor should work. In fact, it does work for small files but I get HEAP CORRUPTION ERROR while working with bigger files. If there is something fundamentally wrong, then, please help me find it, as I have been scratching my head for quit some time now.
Thanks in advance and awaiting reply,
Regards,
Atul
Continued from Y'day :
Further studying this in detail I now have realized that Heap allocation error in my case is because I am allocating something, and then overwriting it with a higher size.
Below is the code where in my data gets populated in the constructor.
CEntity::CEntity(string section1,string section2)
{
size_t length;
char buffer[9];
//Entity Type Number
length = section1.copy(buffer,8,0);
buffer[length]='\0';
m_entity_type = atoi(buffer);
//Parameter Data Count
length = section1.copy(buffer,8,8);
buffer[length]='\0';
m_param_data_pointer = atoi(buffer);
//.... like wise ....
}
I am getting the values at a fixed interval of 8 chars and I am adding a '\0' so this, i guess will take care of any garbage value that I encounter.
About
Heap allocation error: after normal block (XXX) at XXX, CRT detected that application wrote to memory after end of Heap buffer. Mostly, Heap allocation errors occur somewhere else than where it crashes. I would appreciate if some one here would help me, how to make use of this normal block and the address.
Thanks,
| Finally, after two days of debugging, I was able to fix up the crash. It was due to me copying wrong number of characters from the string.
Lessons learnt :
1. When you encounter memory allocation errors, try to form a simple test case which has minimum entities to reproduce the problem.
2. A sure shot way is a line by line debugging. I agree,it test your patience, but then, there are no short cuts to success
3. And it gives you a chance to do a code review, further enhancing the quality of code that you produce in future
Thank you for all your help and formatting my code :)
Regards,
Atul
|
2,447,172 | 2,447,245 | getting window screenshot windows API | I am trying to make a program to work on top of an existing GUI to annotate it and provide extra calculations and statistical information. I want to do this using image recognition, as I have learned a fair amount about this in University using Matlab and similar things. I can get a handle to the window I want to perform image recognition on, but I don't know how to turn that handle into an image of that window, and all its visible child windows. I suppose I am looking for something like the screenshot function, but restricted to a single window.
How would I go about doing this? I suppose I'd need something like a .bmp to mess about with. Also, it would have to be efficient enough that I could call it several times a second without my PC grinding to a halt.
Hopefully this isn't an obvious question, I typed some things into google but didn't get anything related.
| One simple way is using the PrintWindow API (which is an automated Alt + Print basically). The following example takes a screenshot of the calculator, but you would just have to replace the handles.
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle of calculator application.
HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));
// Take screenshot.
PrintWindow( hWnd,
dc.GetSafeHdc(),
0 );
}
(see https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-printwindow )
|
2,447,271 | 2,447,300 | convert perl map with multiple key to c++ | I want to convert a code from perl to c++, and my problem is multi key map in perl!
example:
perl:
$address{name}{familyName} = $someAddress;
and keys are not unique.
I want similar data structure in c++ using map or ...!?
also I want to search and obtain values with first key for example I want such %keys{name} in c++ .
edited: I want to know something like if any family name for special name exists or not , also name and family name together are the key and unique not each of them.
| You want something like:
#include <map>
#include <string>
struct Person {
Person( const std::string & n, const std::string & f )
: name( n ), family( f ) {}
bool operator<( const Person & p ) const {
if ( family < p.family ) return true;
else if ( family == p.family ) return name < p.name;
else return false;
}
std::string name;
std::string family;
};
int main() {
std::multimap <Person, std::string> amap;
amap.insert(
std::make_pair( Person( "fred", "bloggs" ), "somewhere")
);
// alternate, though semantically somewhat different syntax
amap[ Person( "fred", "bloggs" ) ] = "new address";
}
|
2,447,310 | 2,447,381 | Compiling C++ when two classes refer to one another | I am trying to write a simple wrapper around a connection pointer that will return it to the pool when the wrapper is destroyed, but it wont compile because the ConnectionPool and AutoConn need each other to be declared.
I tried to use forward deceleration but it didn't work. How do I solve this? (using g++)
class Connection {};
class ConnectionPool
{
Connection *m_c;
public:
AutoConn getConn()
{
return AutoConn(this, m_c); // by value
}
void releaseConnection(Connection *c)
{
}
};
class AutoConn
{
ConnectionPool* m_pool;
Connection *m_connection;
public:
AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
~AutoConn()
{
m_pool->releaseConnection(m_connection);
}
};
| A combination of forward declaration and separation of declaration from definition of members with circular dependencies works. For example:
class Connection {};
class ConnectionPool ;
class AutoConn
{
ConnectionPool* m_pool;
Connection *m_connection;
public:
AutoConn(ConnectionPool* pool, Connection *c) : m_pool(pool), m_connection(c) {}
~AutoConn() ; // Not defined here because it accesses unknown members of class Connection
} ;
class ConnectionPool
{
Connection *m_c;
public:
AutoConn getConn()
{
return AutoConn(this, m_c); // by value
}
void releaseConnection(Connection *c)
{
}
};
// Definition of destructor with class Connection member dependencies.
AutoConn::~AutoConn()
{
m_pool->releaseConnection(m_connection);
}
|
2,447,392 | 2,448,318 | Does std::vector change its address? How to avoid | Since vector elements are stored contiguously, I guess it may not have the same address after some push_back's , because the initial allocated space could not suffice.
I'm working on a code where I need a reference to an element in a vector, like:
int main(){
vector<int> v;
v.push_back(1);
int *ptr = &v[0];
for(int i=2; i<100; i++)
v.push_back(i);
cout << *ptr << endl; //?
return 0;
}
But it's not necessarily true that ptr contains a reference to v[0], right? How would be a good way to guarantee it?
My first idea would be to use a vector of pointers and dynamic allocation. I'm wondering if there's an easier way to do that?
PS.: Actually I'm using a vector of a class instead of int, but I think the issues are the same.
| Don't use reserve to postpone this dangling pointer bug - as someone who got this same problem, shrugged, reserved 1000, then a few months later spent ages trying to figure out some weird memory bug (the vector capacity exceeded 1000), I can tell you this is not a robust solution.
You want to avoid taking the address of elements in a vector if at all possible precisely because of the unpredictable nature of reallocations. If you have to, use iterators instead of raw addresses, since checked STL implementations will tell you when they have become invalid, instead of randomly crashing.
The best solution is to change your container:
You could use std::list - it does not invalidate existing iterators when adding elements, and only the iterator to an erased element is invalidated when erasing
If you're using C++0x, std::vector<std::unique_ptr<T>> is an interesting solution
Alternatively, using pointers and new/delete isn't too bad - just don't forget to delete pointers before erasing them. It's not hard to get right this way, but you have to be pretty careful to not cause a memory leak by forgetting a delete. (Mark Ransom also points out: this is not exception safe, the entire vector contents is leaked if an exception causes the vector to be destroyed.)
Note that boost's ptr_vector cannot be used safely with some of the STL algorithms, which may be a problem for you.
|
2,447,458 | 2,447,556 | Default template arguments for function templates | Why are default template arguments only allowed on class templates? Why can't we define a default type in a member function template? For example:
struct mycclass {
template<class T=int>
void mymember(T* vec) {
// ...
}
};
Instead, C++ forces that default template arguments are only allowed on a class template.
| It makes sense to give default template arguments. For example you could create a sort function:
template<typename Iterator,
typename Comp = std::less<
typename std::iterator_traits<Iterator>::value_type> >
void sort(Iterator beg, Iterator end, Comp c = Comp()) {
...
}
C++0x introduces them to C++. See this defect report by Bjarne Stroustrup: Default Template Arguments for Function Templates and what he says
The prohibition of default template arguments for function templates is a misbegotten remnant of the time where freestanding functions were treated as second class citizens and required all template arguments to be deduced from the function arguments rather than specified.
The restriction seriously cramps programming style by unnecessarily making freestanding functions different from member functions, thus making it harder to write STL-style code.
|
2,447,696 | 2,447,716 | Overloading assignment operator in C++ | As I've understand, when overloading operator=, the return value should should be a non-const reference.
A& A::operator=( const A& )
{
// check for self-assignment, do assignment
return *this;
}
It is non-const to allow non-const member functions to be called in cases like:
( a = b ).f();
But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?
It's assumed that copy constructor is implemented correctly.
| Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?
a = b; // huh, why does this create an unnecessary copy?
In addition, it would be surprising to users of your class, since the built-in assignment operator doesn't copy likewise
int &a = (some_int = 0); // works
|
2,448,058 | 2,452,672 | Boost.MultiIndex: How to make an effective set intersection? | assume that we have a data1 and data2. How can I intersect them with std::set_intersect()?
struct pID
{
int ID;
unsigned int IDf;// postition in the file
pID(int id,const unsigned int idf):ID(id),IDf(idf){}
bool operator<(const pID& p)const { return ID<p.ID;}
};
struct ID{};
struct IDf{};
typedef multi_index_container<
pID,
indexed_by<
ordered_unique<
tag<IDf>, BOOST_MULTI_INDEX_MEMBER(pID,unsigned int,IDf)>,
ordered_non_unique<
tag<ID>,BOOST_MULTI_INDEX_MEMBER(pID,int,ID)> >
> pID_set;
ID_set data1, data2;
Load(data1); Load(data2);
pID_set::index<ID>::type& L1_ID_index=L1.data.get<ID>();
pID_set::index<ID>::type& L2_ID_index=L2.data.get<ID>();
// How do I use set_intersect?
| std::set_intersection(
L1_ID_index.begin(),L1_ID_index.end(),
L2_ID_index.begin(),L2_ID_index.end(),
output_iterator,
L1_ID_index.value_comp());
|
2,448,155 | 2,448,269 | SetThreadName not working with Visual Studio 2005 | SetThreadName does not set thread name with Visual Studio 2005, when used as below:
DWORD threadId;
HANDLE handle = CreateThread(NULL, stackSize, ThreadFunction,
ThreadParam, CREATE_SUSPENDED, &threadId);
if (handle)
{
SetThreadName(threadId, "NiceName");
ResumeThread(handle);
}
After opening the Threads window, instead of NiceName I can see the name of the ThreadFunction there. Other tools (like Intel Parallel Inspector) use NiceName as expected.
Is something wrong with the code above?
Does the code work with Visual Studio 2008 or 2010 editions?
| After a few experiments I have found it is because the Visual Studio is trying to be smart and when the thread begins to execute it gives a name to itself. The workaround is not to try to give the name to thread before the thread has actually started, the easiest way how to achieve this is to call the SetThreadName from inside of the thread function.
Still I would be interested in knowing if other versions of Visual Studio show the same behaviour.
|
2,448,160 | 2,448,478 | Looking for design advise - Statistics reporter | I need to implement a statistics reporter - an object that prints to screen bunch of statistic.
This info is updated by 20 threads.
The reporter must be a thread itself that wakes up every 1 sec, read the info and prints it to screen.
My design so far: InfoReporterElement - one element of info. has two function, PrintInfo and UpdateData.
InfoReporterRow - one row on screen. A row holds vector of ReporterInfoElement.
InfoReporterModule - a module composed of a header and vector of rows.
InfoRporter - the reporter composed of a vector of modules and a header. The reporter exports the function 'PrintData' that goes over all modules\rows\basic elements and prints the data to screen.
I think that I should an Object responsible to receive updates from the threads and update the basic info elements.
The main problem is how to update the info - should I use one mutex for the object or use mutex per basic element?
Also, which object should be a threads - the reporter itself, or the one that received updates from the threads?
| I would say that first of all, the Reporter itself should be a thread. It's basic in term of decoupling to isolate the drawing part from the active code (MVC).
The structure itself is of little use here. When you reason in term of Multithread it's not so much the structure as the flow of information that you should check.
Here you have 20 active threads that will update the information, and 1 passive thread that will display it.
The problem here is that you encounter the risk of introducing some delay in the work to be done because the active thread cannot acquire the lock (used for display). Reporting (or logging) should never block (or as little as possible).
I propose to introduce an intermediate structure (and thread), to separate the GUI and the work: a queuing thread.
active threads post event to the queue
the queuing thread update the structure above
the displaying thread shows the current state
You can avoid some synchronization issues by using the same idea that is used for Graphics. Use 2 buffers: the current one (that is displayed by the displaying thread) and the next one (updated by the queuing thread). When the queuing thread has processed a batch of events (up to you to decide what a batch is), it asks to swap the 2 buffers, so that next time the displaying thread will display fresh info.
Note: On a more personal note, I don't like your structure. The working thread has to know exactly where on the screen the element it should update is displayed, this is a clear breach of encapsulation.
Once again, look up MVC.
And since I am neck deep in patterns: look up Observer too ;)
|
2,448,242 | 2,448,307 | Struct with template variables in C++ | I'm playing around with templates. I'm not trying to reinvent the std::vector, I'm trying to get a grasp of templateting in C++.
Can I do the following?
template <typename T>
typedef struct{
size_t x;
T *ary;
}array;
What I'm trying to do is a basic templated version of:
typedef struct{
size_t x;
int *ary;
}iArray;
It looks like it's working if I use a class instead of struct, so is it not possible with typedef structs?
| The problem is you can't template a typedef, also there is no need to typedef structs in C++.
The following will do what you need
template <typename T>
struct array {
size_t x;
T *ary;
};
|
2,448,302 | 2,448,457 | container won't sort, test case included, (easy question?) | I can't see what I'm doing wrong. I think it might be one of the Rule of Three methods. Codepad link
#include <deque>
//#include <string>
//#include <utility>
//#include <cstdlib>
#include <cstring>
#include <iostream>
//#include <algorithm> // I use sort(), so why does this still compile when commented out?
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace fs = boost::filesystem;
class Page
{
public:
// constructor
Page(const char* path, const char* data, int size) :
path_(fs::path(path)),
size_(size),
data_(new char[size])
{
// cout << "Creating Page..." << endl;
strncpy(data_, data, size);
// cout << "done creating Page..." << endl;
}
// copy constructor
Page(const Page& other) :
path_(fs::path(other.path())),
size_(other.size()),
data_(new char[other.size()])
{
// cout << "Copying Page..." << endl;
strncpy(data_, other.data(), size_);
// cout << "done copying Page..." << endl;
}
// destructor
~Page() { delete[] data_; }
// accessors
const fs::path& path() const { return path_; }
const char* data() const { return data_; }
int size() const { return size_; }
// operators
Page& operator = (const Page& other) {
if (this == &other)
return *this;
char* newImage = new char[other.size()];
strncpy(newImage, other.data(), other.size());
delete[] data_;
data_ = newImage;
return *this;
}
bool operator < (const Page& other) const { return path_ < other.path(); }
private:
fs::path path_;
int size_;
char* data_;
};
class Book
{
public:
Book(const char* path) :
path_(fs::path(path))
{
cout << "Creating Book..." << endl;
cout << "pushing back #1" << endl;
pages_.push_back(Page("image1.jpg", "firstImage", 10));
cout << "pushing back #3" << endl;
pages_.push_back(Page("image3.jpg", "thirdImage", 10));
cout << "pushing back #2" << endl;
pages_.push_back(Page("image2.jpg", "secondImage", 11));
cout << "testing operator <" << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[1]? " < " : " > ") << pages_[1].path().string() << endl;
cout << pages_[1].path().string() << (pages_[1] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << "sorting" << endl;
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
sort(pages_.begin(), pages_.end());
cout << "done sorting\n";
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
cout << "done Creating Book" << endl;
}
private:
deque<Page> pages_;
fs::path path_;
};
int main() {
Book* book = new Book("/some/path/");
}
| I just kept messing around, and realized that my assignment operator needs to copy all the other parameters over as well, not just the heap allocated ones.
Man do I feel dumb. >_<
Btw followup question: Is there a way to do the sorting without needing to strncpy() all the buffers and just swap the pointer addresses around instead?
edit:
tnx dirkgently. Yeah that's what it was, sry didn't see your comment before I posted this.
|
2,448,380 | 2,448,431 | C++ expected constant expression | #include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <iomanip>
using std::ifstream;
using namespace std;
int main (void)
{
int count=0;
float sum=0;
float maximum=-1000000;
float sumOfX;
float sumOfY;
int size;
int negativeY=0;
int positiveX=0;
int negativeX=0;
ifstream points; //the points to be imported from file
//points.open( "data.dat");
//points>>size;
//cout<<size<<endl;
size=100;
float x[size][2];
while (count<size) {
points>>(x[count][0]);
//cout<<"x= "<<(x[count][0])<<" ";//read in x value
points>>(x[count][1]);
//cout<<"y= "<<(x[count][1])<<endl;//read in y value
count++;
}
This program is giving me expected constant expression error on the line where I declare float x[size][2]. Why?
| float x[size][2];
That doesn't work because declared arrays can't have runtime sizes. Try a vector:
std::vector< std::array<float, 2> > x(size);
Or use new
// identity<float[2]>::type *px = new float[size][2];
float (*px)[2] = new float[size][2];
// ... use and then delete
delete[] px;
If you don't have C++11 available, you can use boost::array instead of std::array.
If you don't have boost available, make your own array type you can stick into vector
template<typename T, size_t N>
struct array {
T data[N];
T &operator[](ptrdiff_t i) { return data[i]; }
T const &operator[](ptrdiff_t i) const { return data[i]; }
};
For easing the syntax of new, you can use an identity template which effectively is an in-place typedef (also available in boost)
template<typename T>
struct identity {
typedef T type;
};
If you want, you can also use a vector of std::pair<float, float>
std::vector< std::pair<float, float> > x(size);
// syntax: x[i].first, x[i].second
|
2,448,463 | 2,448,500 | Vector of vectors of T in template<T> class | Why this code does not compile (Cygwin)?
#include <vector>
template <class Ttile>
class Tilemap
{
typedef std::vector< Ttile > TtileRow;
typedef std::vector< TtileRow > TtileMap;
typedef TtileMap::iterator TtileMapIterator; // error here
};
error: type std::vector<std::vector<Ttile, std::allocator<_CharT> >, std::allocator<std::vector<Ttile, std::allocator<_CharT> > > >' is not derived from typeTilemap'
| Because the TtileMap::iterator is not known to be a type yet. Add the typename keyword to fix it
typedef typename TtileMap::iterator TtileMapIterator;
|
2,448,501 | 2,448,567 | Does the compiler optimize the function parameters passed by value? | Lets say I have a function where the parameter is passed by value instead of const-reference. Further, lets assume that only the value is used inside the function i.e. the function doesn't try to modify it. In that case will the compiler will be able to figure out that it can pass the value by const-reference (for performance reasons) and generate the code accordingly? Is there any compiler which does that?
| If you pass a variable instead of a temporary, the compiler is not allowed to optimize away the copy if the copy constructor of it does anything you would notice when running the program ("observable behavior": inputs/outputs, or changing volatile variables).
Apart from that, the compiler is free to do everything it wants (it only needs to resemble the observable behavior as-if it wouldn't have optimized at all).
Only when the argument is an rvalue (most temporary), the compiler is allowed to optimize the copy to the by-value parameter even if the copy constructor has observable side effects.
|
2,448,715 | 2,466,675 | Verbosity in boost asio using ssl | Is there a way to make ssl handshake more visible to me using boost asio?
I am getting an error: "asio.ssl error".
I just want more verbosity, because this message means almost nothing to me.
| I found that boost.asio with ssl use openssl.
I just need to recompile the libssl with debug flags to make ssl handshake process more verbose. I can do this just reconfiguring with './config -DKSSL_DEBUG'.
In the boost documentation I found no way to control the verbosity level.
|
2,448,738 | 2,448,846 | How to force a window to maintain a certain width/height ratio when resized | I want my window to always maintain a certain ratio of let's say 1.33333333. So, if the window is width = 800, height = 600 and the user changes the width to 600, I want to change the height to 450 automatically.
I'm already intercepting WM_SIZE but I don't know if it's enough; also I don't know how to change the width or height to maintain my ratio.
| WM_SIZING is sent to the window while the user is resizing the window.
Rather handle WM_WINDOWPOSCHANGING - this is sent by the internal SetWindowPos function when code (or the user) changes the window size and will ensure that even tile & cascade operations obey your sizing policy.
|
2,448,802 | 2,449,201 | Chaining multiple ShellExecute calls | Consider the following code and its executable - runner.exe:
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
SHELLEXECUTEINFO shExecInfo;
shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shExecInfo.fMask = NULL;
shExecInfo.hwnd = NULL;
shExecInfo.lpVerb = "open";
shExecInfo.lpFile = argv[1];
string Params = "";
for ( int i = 2; i < argc; ++i )
Params += argv[i] + ' ';
shExecInfo.lpParameters = Params.c_str();
shExecInfo.lpDirectory = NULL;
shExecInfo.nShow = SW_SHOWNORMAL;
shExecInfo.hInstApp = NULL;
ShellExecuteEx(&shExecInfo);
return 0;
}
These two batch files both do what they're supposed to, which is run notepad.exe and run notepad.exe and tell it to try to open test.txt:
1.
runner.exe notepad.exe
2.
runner.exe notepad.exe test.txt
Now, consider this batch file:
3.
runner.exe runner.exe notepad.exe
This one should run runner.exe and send notepad.exe as one of its command line arguments, shouldn't it? Then, that second instance of runner.exe should run notepad.exe - which doesn't happen, I get a "Windows cannot find 'am'. Make sure you typed the name correctly, and then try again" error. If I print the argc argument, it's 14 for the second instance of runner.exe, and they are all weird stuff like Files\Microsoft, SQL, Files\Common and so on. I can't figure out why this happens. I want to be able to string as many runner.exe calls using command line arguments as possible, or at least 2. How can I do that?
I am using Windows 7 if that makes a difference.
| You have a bug in this line:
Params += argv[i] + ' ';
This will add 32 to the pointer argv[i], which isn't what you want. You can separate it to two lines:
Params += argv[i];
Params += ' ';
Or use:
Params += string(argv[i]) + ' ';
You may also want to add quotes around each parameter in case it contains spaces.
I'd also set fMask to SEE_MASK_NOASYNC, because MSDN states:
Applications that exit immediately after calling ShellExecuteEx should specify this flag.
|
2,448,823 | 2,448,860 | Program compiled with MSVC 9 won't start on a vanilla SP3 XP | I installed XP on a virtual machine, updated it to SP3 and then tested a small program compiled with Visual C++ 2008 on my real computer - however it didn't start but outputted only an error saying that a problem had been detected and that a reinstall of the application (mine is 10KB in size and doesn't even have an installation) could fix the problem.
What is required to run programs compiled with MSVC 9?
Can I just include some dlls for it to work everywhere?
| Either link statially against the runtime library (select multithreaded instead of multithreaded-dll) or follow tommieb75's advice and install the MSVC9 runtime redistributable (copying to system32 or to the application's folder works as well, but is not the way to go, afaik). For small applications with no need for an installer, I'd prefer the first option. Deploying runtime installers is annoying.
|
2,448,879 | 2,448,962 | When will DllMain be called with the DLL_PROCESS_VERIFIER flag? | On Windows, the standard DLL entry point is called DllMain. The second parameter is a DWORD, ul_reason_for_call.
I have looked up the possible values for this second parameter on MSDN. The following are obvious:
DLL_PROCESS_ATTACH:
DLL_THREAD_ATTACH:
DLL_THREAD_DETACH:
DLL_PROCESS_DETACH:
But what about:
DLL_PROCESS_VERIFIER
When will the entry point be called with this flag? Should I worry about it during 'normal' operation of the DLL?
Note that I only see DLL_PROCESS_VERIFIER in header files from Visual Studio 2005, not 2008.
| I guess in theory Microsoft could invent new usages and flags any time they feel they need a new one. So the simple rule is to ensure that your code tolerates unexpected values: i.e. write it to handle the cases that you need to handle and ignore the rest, by returning zero.
|
2,449,159 | 2,449,654 | Linux time sample based profiler | short version:
Is there a good time based sampling profiler for Linux?
long version:
I generally use OProfile to optimize my applications. I recently found a shortcoming that has me wondering.
The problem was a tight loop, spawning c++filt to demangle a c++ name. I only stumbled upon the code by accident while chasing down another bottleneck. The OProfile didn't show anything unusual about the code so I almost ignored it but my code sense told me to optimize the call and see what happened. I changed the popen of c++filt to abi::__cxa_demangle. The runtime went from more than a minute to a little over a second. About a x60 speed up.
Is there a way I could have configured OProfile to flag the popen call? As the profile data sits now OProfile thinks the bottle neck was the heap and std::string calls (which BTW once optimized dropped the runtime to less than a second, more than x2 speed up).
Here is my OProfile configuration:
$ sudo opcontrol --status
Daemon not running
Event 0: CPU_CLK_UNHALTED:90000:0:1:1
Separate options: library
vmlinux file: none
Image filter: /path/to/executable
Call-graph depth: 7
Buffer size: 65536
Is there another profiler for Linux that could have found the bottleneck?
I suspect the issue is that OProfile only logs its samples to the currently running process. I'd like it to always log its samples to the process I'm profiling. So if the process is currently switched out (blocking on IO or a popen call) OProfile would just place its sample at the blocked call.
If I can't fix this, OProfile will only be useful when the executable is pushing near 100% CPU. It can't help with executables that have inefficient blocking calls.
| Glad you asked. I believe OProfile can be made to do what I consider the right thing, which is to take stack samples on wall-clock time when the program is being slow and, if it won't let you examine individual stack samples, at least summarize for each line of code that appears on samples, the percent of samples the line appears on. That is a direct measure of what would be saved if that line were not there. Here's one discussion. Here's another, and another. And, as Paul said, Zoom should do it.
If your time went from 60 sec to 1 sec, that implies every single stack sample would have had a 59/60 probability of showing you the problem.
|
2,449,271 | 2,449,330 | How to iterate on boost::mutable_queue | I need a priority queue where I can increase or decrease the priority key. So boost::mutable_queue seemed perfect despite the lack of documentation.
The problem is that I need to iterate at some point over all the elements in the queue. How can I do that?
Or is there an othe data structure that would work (preferably in boost)?
| Queues are not for iteration. The whole point of a queue is that you can only ever look at the element at the front of the queue.
If you want to iterate then I suggest just using an std::set, which is ordered. When you want to modify an element, you'll have to remove it and reinsert it with the new key. You can get the highest priority element using mySet.begin() (that returns an iterator to it).
Ideally, you'll want to use a heap. STL provides functions for making heaps, and that's what the std::priority_queue uses. However, you can't modify keys in the heap because there is no interface for it.
If you manage the heap yourself then you can. However, you'll need to make use of the std::__adjust_heap function from <heap.h>, which is undocumented. You can read all about why this function is undocumented in this interview with Alexander Stepanov (inventor of the STL). It had to be "removed" because apparently the STL was too big, which is also what happened to hash maps from the original standard.
|
2,449,386 | 2,449,404 | What does deleting a pointer mean? | Is deleting a pointer same as freeing a pointer (that allocates the memory)?
| Deleting a pointer (or deleting what it points to, alternatively) means
delete p;
delete[] p; // for arrays
p was allocated prior to that statement like
p = new type;
It may also refer to using other ways of dynamic memory management, like free
free(p);
which was previously allocated using malloc or calloc
p = malloc(size);
The latter is more often referred to as "freeing", while the former is more often called "deleting". delete is used for classes with a destructor since delete will call the destructor in addition to freeing the memory. free (and malloc, calloc etc) is used for basic types, but in C++ new and delete can be used for them likewise, so there isn't much reason to use malloc in C++, except for compatibility reasons.
|
2,449,405 | 2,449,773 | How can I declare constant strings for use in both an unmanaged C++ dll and in a C# application? | Curently I'm passing my const string values up from my C++ into my C# at startup via a callback, but I'm wondering if there's a way of defining them in a C++ header file that I can then also refer to in C#.
I already do this with enums as they are easy.
I include a file in both my C++ library project (via a .h file with a pragma once at the top), and my C# application (as a link):
#if _NET
public
#endif
enum ETestData
{
First,
Second
};
I know it sounds messy, but it works :)
But...how can I do the same with string constants - I'm initially thinking the syntax is too different between the platforms, but maybe there's a way?
Using clever syntax involving #if _NET, #defines etc?
Using resource files?
Using a C++/CLI library?
Any ideas?
| Call me funny, but I think the best way to do this is using C++/CLI and C++.
This lets you #include the same strings into two different contexts and let the compiler do the magic.
This will give you arrays of strings
// some header file
L"string1",
L"string2",
L"string3",
// some C++ file
static wchar_t*[] string = {
#include "someheaderfile.h"
};
// in some C++/CLI file
array<String^>^ myArray = gcnew array<String^> {
#include "someheaderfile.h"
};
otherwise you can use the C preprocessor straight out:
// in somedefineset
#define SOME_STRING_LITERAL L"whatever"
// in some C++ file
#include "somedefineset.h"
const wchar_t *kSomeStringLiteral = SOME_STRING_LITERAL
// in some C++/CLI file
literal String ^kSomeStringLiteral = SOME_STRING_LITERAL;
|
2,449,578 | 2,449,617 | Implicit casting Integer calculation to float in C++ | Is there any compiler that has a directive or a parameter to cast integer calculation to float implicitly. For example:
float f = (1/3)*5;
cout << f;
the "f" is "0", because calculation's constants(1, 3, 10) are integer. I want to convert integer calculation with a compiler directive or parameter. I mean, I won't use explicit casting or ".f" prefix like that:
float f = ((float)1/3)*5;
or
float f = (1.0f/3.0f)*5.0f;
Do you know any c/c++ compiler which has any parameter to do this process without explicit casting or ".f" thing?
| If you don't like either of the two methods you mentioned, you're probably out of luck.
What are you hoping to accomplish with this? Any specialized operator that did "float-division" would have to convert ints to floats at some point after tokenization, which means you're not going to get any performance benefit on the execution.
|
2,450,155 | 2,450,211 | C++ Perfect Number. Need some help revising | I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter a positive integer in order to define whether it is a perfect integer or not: " ;
cin >> perfect;
cout << endl;
int temp = 0;
int prevtemp = 0;
limit = 1;
divisor = 1;
while (limit < perfect)
{
if ((perfect % divisor) == 0)
{
divisor = prevtemp;
temp = prevtemp + temp;
}
limit++;
divisor++;
}
if (perfect == temp)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
return 0;
| I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limit is intended to accomplish -- you initialize it and increment it, but as far as I can see, you never use its value (well, I guess you use it, but its value is always the same as divisor's so I'm not sure why you think you need both, or how limit makes any sense as its name).
Edit: It would make sense to have a limit. In particular, factors always come in pairs: one that's less than or equal to the square root of the number, and one that matches the first that's always greater than or equal to the square root of the number. As such, you don't need to scan all the way up to the number itself looking for factors -- you can set the square root of the number as the limit, and scan only up to that point. For each factor you find up to that point, the matching factor will be perfect/divisor. Since you've already gotten one working example, I guess I might as well just hope this isn't homework, and post an example as well:
bool is_perfect(int number) {
int limit = sqrt((double)number);
int sum = 1;
for (int i=2; i<=limit; i++)
if (number % i == 0)
sum += i + number/i;
return sum == number;
}
|
2,450,270 | 2,480,875 | Getting a shared pointer to a derived class when base class inherits from enable_shared_from_this | I have a class B which inherits from A which in turn derives from enabled_shared_from_this. Now, I want to get a shared pointer to B from an instance of B. shared_from_this will return shared_ptr<A>, not shared_ptr<B>. Should I use boost::static_pointer_cast here? Or is there a better way?
| This seems to be a valid approach as the type is known at compile time.
|
2,450,279 | 2,450,357 | How to set bit values which are not divided on byte boundary | I have a header field of 2 bytes where first four bits are packet type and other 12 bits are for length. but i don't know how to store this values and retrieve them.
I am using ms c++ for client and java for server. It is the client which has to set this values and server has to retrieve it.
Thanks
| Storing
unsigned short get_header(unsigned char type, unsigned short length)
{
return (static_cast<unsigned short>(type) << 12) | length;
}
Retrieving (from unsigned short)
unsigned short header = /* get 2 header bytes */
unsigned char type = header >> 12;
unsigned short length = header & 0xFFF;
Retrieving (from unsigned char[2])
unsigned char bytes[2] = /* get 2 header bytes */
unsigned char type = bytes[0] >> 4;
unsigned short length = bytes[0] & 0xF | bytes[1];
|
2,450,340 | 2,450,451 | Ignore carriage returns in scanf before data.... to keep layout of console based graphics with conio.h | I have the misfortune of having use conio.h in vc++ 6 for a college assignment,
My problem is that my graphic setup is in the center of the screen...
e.g.
gotoxy( getcols()/2, getrows()/2);
printf("Enter something");
scanf( "%d", &something );
now if someone accidentally hits enter before they enter the "something", then the cursor gets reset to the left of the screen on the next line.
Iv tried flushing the keyboard and bios buffers with fflush(stdin) and getchar(), which like I expected didn't work!
Any help/ideas would be appreciated,
Thanks,
V
| The road to success will involve doing what the assignment asks you to do :) In particular, you should use one or more functions from conio.h to read your input. scanf() is not a conio.h function.
Because I'm lazy this is a homework question, I won't write the code for you.
One possibility would be to use cscanf() rather than scanf(). But this may (I don't know) echo input characters, which would include that accidental Enter, and not solve your problem.
If this is the case, my strategy would be to write a loop to gather characters entered from the keyboard, using the non-echoing getch() function. You can ignore newlines until you have at least one printable character, and then accept characters (and store them in a character array or whatever) until you get a newline. Since input characters won't be echoed, I think the cursor will not move.
You can then scan the input characters from your input buffer using sscanf(). You'll want to count input characters to make sure your user doesn't overflow your buffer. Also, probably some error handling in case of bad data.
EDIT: Something I forgot to mention: Your last input character in the buffer should be followed by a zero character ( '\0' ) so sscanf() will terminate properly. It's possible for your buffer to be full of zeros by default, but putting one in there intentionally (e.g. when you hit your final newline) will make your code more correct and robust.
|
2,450,408 | 2,450,437 | How to implement a network protocol? | Here is a generic question. I'm not in search of the best answer, I'd just like you to express your favourite practices.
I want to implement a network protocol in Java (but this is a rather general question, I faced the same issues in C++), this is not the first time, as I have done this before. But I think I am missing a good way to implement it. In fact usually it's all about exchanging text messages and some byte buffers between hosts, storing the status and wait until the next message comes. The problem is that I usually end up with a bunch of switch and more or less complex if statements that react to different statuses / messages. The whole thing usually gets complicated and hard to mantain. Not to mention that sometimes what comes out has some "blind spot", I mean statuses of the protocol that have not been covered and that behave in a unpredictable way. I tried to write down some state machine classes, that take care of checking start and end statuses for each action in more or less smart ways. This makes programming the protocol very complicated as I have to write lines and lines of code to cover every possible situation.
What I'd like is something like a good pattern, or a best practice that is used in programming complex protocols, easy to mantain and to extend and very readable.
What are your suggestions?
| Read up on the State design pattern to learn how to avoid lots of switch statements.
"sometimes what comes out has some "blind spot", I mean statuses of the protocol that have not been covered..."
State can help avoid gaps. It can't guarantee a good design, you still have to do that.
"...as I have to write lines and lines of code to cover every possible situation."
This should not be considered a burden or a problem: You must write lines of code to cover every possible situation.
State can help because you get to leverage inheritance. It can't guarantee a good design, you still have to do that.
|
2,450,982 | 2,451,012 | C++ stl collections or linked lists | I'm developing a OpenGL based simulation in C++. I'm optmizing my code now and i see throughout the code the frequently use of std:list and std:vector. What is the more performatic: to continue using C++ stl data structs or a pointer based linked list? The main operation that involve std::list and std::vector is open a iterator and loop through all items in the data structs and apply some processing
| How about stl containers of pointers?
It is highly unlikely that you will be able to develop better performing structures than the builtin. The only down part is the containers actually do contain copies of objects stored in them. If you're worried about this memory overhead (multiple structs hodling multiple copies of same objects, breaking consistency across the table) you should think about using stl structures of pointers to what you need.
Algorithmically speaking, the structure you need is implemented in the stl so you should use it. There is no need to reimplement the same structure.
|
2,451,103 | 2,451,190 | Use WM_COPYDATA to send data between processes | I wish to send text between processes. I have found lots of examples of this but none that I can get working. Here is what I have so far:
for the sending part:
COPYDATASTRUCT CDS;
CDS.dwData = 1;
CDS.cbData = 8;
CDS.lpData = NULL;
SendMessage(hwnd, WM_COPYDATA , (WPARAM)hwnd, (LPARAM) (LPVOID) &CDS);
the receiving part:
case WM_COPYDATA:
COPYDATASTRUCT* cds = (COPYDATASTRUCT*) lParam;
I dont know how to construct the COPYDATASTRUCT, I have just put something in that seems to work. When debugging the WM_COPYDATA case is executed, but again I dont know what to do with the COPYDATASTRUCT.
I would like to send text between the two processes.
As you can probably tell I am just starting out, I am using GNU GCC Compiler in Code::Blocks, I am trying to avoid MFC and dependencies.
| For an example of how to use the message, see http://msdn.microsoft.com/en-us/library/ms649009(VS.85).aspx. You may also want to look at http://www.flounder.com/wm_copydata.htm.
The dwData member is defined by you. Think of it like a data type enum that you get to define. It is whatever you want to use to identify that the data is a such-and-such string.
The cbData member is the size in bytes of the data pointed to by lpData. In your case, it will be the size of the string in bytes.
The lpData member points to the data you want to copy.
So, to transfer a single string....
LPCTSTR lpszString = ...;
COPYDATASTRUCT cds;
cds.dwData = 1; // can be anything
cds.cbData = sizeof(TCHAR) * (_tcslen(lpszString) + 1);
cds.lpData = lpszString;
SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)(LPVOID)&cds);
Then, to receive it....
COPYDATASTRUCT* pcds = (COPYDATASTRUCT*)lParam;
if (pcds->dwData == 1)
{
LPCTSTR lpszString = (LPCTSTR)(pcds->lpData);
// do something with lpszString...
}
|
2,451,175 | 2,451,212 | C++: Vector3 type "wall"? | Say I have:
class Vector3 {
float x, y, z;
... bunch of cuntions ..
static operator+(const Vector3&, const Vector3);
};
Now, suppose I want to have classes:
Position, Velocity,
that are exactly like Vector3 (basically, I want
typedef Vector3 Position;
typedef Vector3 Velocity;
Except, given:
Position position;
Vector3 vector3;
Velocity velocity;
I want to make sure the following can't happen:
position + vector3;
vector3 + velocity;
velocity + position;
What is the best way to achieve this?
| I would recommend something like this:
template<typename tag>
class Vector3 {
float x, y, z;
... bunch of functions ..
static operator+(const Vector3&, const Vector3);
};
struct position_tag {};
struct velocity_tag {};
typedef Vector3<position_tag> Position;
typedef Vector3<velocity_tag> Velocity;
See here for a more elaborate example: Boost MPL
|
2,451,209 | 2,456,604 | How could I redirect stdin (istream) in wxWidgets? | I'm trying to figure out how to redirect istream to wxwidgets.
I was able to accomplish redirecting ostream, here's how (so you know what I mean):
wxTextCtrl* stdoutctrl = new wxTextCtrl(...);
wxStreamToTextRedirector redirect(stdoutctrl); //Redirect ostream
std::cout<<"stdout -- does this work?"<<std::endl; //It worked.
I've been searching for sometime now, and I'm unable to find out I'd redirect istream to some sort of wx-input (so a "cin" would actually prompt the user for input via wxWidgets).
| No, there is no built in way to do this as it's much less common to want to redirect cin like this compared to cout. And it's also not really clear how do you expect it to work, i.e. you probably can't just map it to a wxTextCtrl as you do with cout. And more generally, reading is a blocking operation, unlike writing, so it's not clear at all how can you structure your GUI application to do it.
In short, I don't think you can port your console program using cin to wxWidgets like this at all.
|
2,451,214 | 2,451,224 | C++ Why is the converter constructor implicitly called? | Why is the Child class's converter constructor called in the code below?
I mean, it automatically converts Base to Child via the Child converter constructor. The code below compiles, but shouldn't it not compile since I haven't provided bool Child::operator!=(Base const&)?
class Base
{
};
class Child : public Base
{
public:
Child() {}
Child(Base const& base_) :
Base(base_)
{
std::cout <<"should never called!";
}
bool operator!=(Child const&)
{
return true;
}
};
void main()
{
Base base;
Child child;
if(child != base)
std::cout << "not equal";
else
std::cout << "equal";
}
| Because you provided a conversion constructor. If you don't want the compiler to automatically convert Base objects to Child using the
Child(Base const& base_)
constructor, make it explicit:
explicit Child(Base const& base_)
This way, the constructor will only be called when you explicitly specify it, in contexts like:
Child ch(base);
foo(Child(base));
new Child(base);
|
2,451,370 | 2,451,378 | Write a function in c that includes the following sequence of statements [Wont Compile] | There is a question in my programming languages textbook that is as follows:
Write a C function that includes the
following sequence of statements:
x = 21;
int x;
x = 42;
Run the program and explain the
results. Rewrite the same code in C++
and Java and compare the results.
I have written code, and played with it in all three languages but I can not even get it to compile. This includes declaring x above the three lines as well as in the calling function (as this question is obviously attempting to illustrate scoping issues)
I'd like to explain the results and do the comparisons on my own, as it is an assignment question but I was wondering if anyone had any insight as to how to get this code to compile?
Thanks
| Note the following requires C99:
int x;
void foo()
{
x = 21;
int x;
x = 42;
}
Since this is homework, you'll need to provide your own explanation.
|
2,451,415 | 2,451,701 | Why can't I input the integers from a file? | I'm trying to get this C++ code to input a series of numbers from a text file:
int x = 0;
cin >> x;
ifstream iffer;
int numbers[12];
iffer.open("input.txt");
for (int i = 0; i < 12; i++){
iffer >> numbers[i];
}
This doesn't seem to work on the Mac.
Every cell will equal to 0 regardless of the values in the text file. In other words, the ifstream isn't assigning the numbers.
How can I make this work? Is it a Mac issue and if so, how can I get it to work?
Thanks!
Anthony Glyadchenko
| I tried your code, slightly modified, on both Linux (g++ 3.4.4) and Mac (g++ 4.0.1) and it works just fine!
With respect to Chuck, if input.txt does not exist, iffer.fail() is true. Since you say that's not the case...
Another possibility is a different input.txt file than what you expected. If it had too few numbers, you'd see zeros (or other garbage values). (You could test with iffer.eof(), though that might be set (appropriately) after reading the last number if there's no trailing whitespace (like a newline). So test eof() before reading!)
Alternatively, you could have a dangling pointer elsewhere in your code trashing something inappropriately. Sometimes adding and removing large chunks of code will permit you to manually "binary search" for where such problems actually lie.
#include <iostream>
#include <fstream>
using namespace std;
#define SHOW(X) cout << # X " = \"" << (X) << "\"" << endl
int main()
{
int x = 0;
cin >> x;
ifstream iffer;
int numbers[12];
iffer.open("input.txt");
SHOW( iffer.fail() );
SHOW( iffer.eof() );
for (int i = 0; i < 12; ++i)
{
SHOW(i);
SHOW(numbers[i]);
iffer >> numbers[i];
SHOW(numbers[i]) << endl;
}
for (int i = 0; i < 12; ++i)
SHOW(numbers[i]);
SHOW( iffer.fail() );
SHOW( iffer.eof() );
}
|
2,451,548 | 2,451,784 | iPhone - OpenGL using C++ tutorial/snippet | Is there any good tutorial or code snippet out there on how to use OpenGL via C/C++ on the iPhone?
| http://developer.apple.com/iphone/library/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html
I'm pretty sure you need a bit of Objective-C to create the context and do other initialization stuff. The rest is also usable in C++.
|
2,451,624 | 2,451,674 | How to get unsigned equivalent of an integral type in C++? | Is there a way to get an unsigned equivalent (same size) of a signed integral type in C++? I'm thinking along the lines of:
template<typename T>
struct get_unsigned { };
template<>
struct get_unsigned<int> {
typedef unsigned int type;
};
...
template<typename T>
void myfunc(T val) {
get_unsigned<T>::type u = std::abs(val);
...
}
I'm looking for an existing solution in the standard library or Boost and prefer not to roll my own unless it's a handful of lines.
| Boost.TypeTraits has make_unsigned:
type: If T is a unsigned integer type then the same type as T, if T is an signed integer type then the corresponding unsigned type. Otherwise if T is an enumerated or character type (char or wchar_t) then an unsigned integer type with the same width as T.
If T has any cv-qualifiers then these are also present on the result type.
The source is much more than a handful of lines.
|
2,451,681 | 2,451,700 | Why do I need to include both the iostream and fstream headers to open a file | #include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("test.txt");
return 0;
}
fstream is derived from iostream, why should we include both in the code above?
I removed fstream, however, there is an error with ofstream. My question is ofstream is derived from ostream, why fstream is needed to make it compile?
| You need to include fstream because that's where the definition of the ofstream class is.
You've kind of got this backwards: since ofstream derives from ostream, the fstream header includes the iostream header, so you could leave out iostream and it would still compile. But you can't leave out fstream because then you don't have a definition for ofstream.
Think about it this way. If I put this in a.h:
class A {
public:
A();
foo();
};
And then I make a class that derives from A in b.h:
#include <a.h>
class B : public A {
public:
B();
bar();
};
And then I want to write this program:
int main()
{
B b;
b.bar();
return 0;
}
Which file would I have to include? b.h obviously. How could I include only a.h and expect to have a definition for B?
Remember that in C and C++, include is literal. It literally pastes the contents of the included file where the include statement was. It's not like a higher-level statement of "give me everything in this family of classes".
|
2,451,714 | 2,451,890 | Access Violation When Accessing an STL Object Through A Pointer or Reference In A Different DLL or EXE | I experience the following problem while using legacy VC6. I just cann't switch to modern compiler, as I am working on a legacy code base.
http://support.microsoft.com/kb/172396
Since there are no way to export map, my planned workaround is using static linking instead of dynamic linking.
I was wondering whether you all had encountered the similar situation? What is your workaround for this?
Another workaround is to create wrapper class around the stl map, to ensure creation and accessing stl map, are within the same DLL space. Note that, fun0, which uses wrapper class will just work fine. fun1 will crash.
Here is the code example :
// main.cpp. Compiled it as exe.
#pragma warning (disable : 4786)
#include <map>
#include <string>
template <class K, class V>
class __declspec(dllimport) map_wrapper {
public:
map_wrapper();
~map_wrapper();
map_wrapper(const map_wrapper&);
map_wrapper& operator=(const map_wrapper&);
V& operator[](const K&);
const V& operator[](const K&) const;
const V& get(const K&) const;
void put(const K&, const V&);
int size() const;
private:
std::map<K, V> *m;
};
__declspec(dllimport) void fun0(map_wrapper<std::string, int>& m);
__declspec(dllimport) void fun1(std::map<std::string, int>& m);
int main () {
map_wrapper<std::string, int> m0;
std::map<std::string, int> m1;
m0["hello"] = 888;
m1["hello"] = 888;
// Safe. The we create std::map and access map both in dll space.
fun0(m0);
// Crash! The we create std::map in exe space, and access map in dll space.
fun1(m1);
return 0;
}
// dll.cpp. Compiled it as dynamic dll.
#pragma warning (disable : 4786)
#include <map>
#include <string>
#include <iostream>
/* In map_wrapper.h */
template <class K, class V>
class __declspec(dllexport) map_wrapper {
public:
map_wrapper();
~map_wrapper();
map_wrapper(const map_wrapper&);
map_wrapper& operator=(const map_wrapper&);
V& operator[](const K&);
const V& operator[](const K&) const;
const V& get(const K&) const;
void put(const K&, const V&);
int size() const;
private:
std::map<K, V> *m;
};
/* End */
/* In map_wrapper.cpp */
template <class K, class V>
map_wrapper<K, V>::map_wrapper() : m(new std::map<K, V>()) {
}
template <class K, class V>
map_wrapper<K, V>::~map_wrapper() {
delete m;
}
template <class K, class V>
map_wrapper<K, V>::map_wrapper(const map_wrapper<K, V>& map) : m(new std::map<K, V>(*(map.m))) {
}
template <class K, class V>
map_wrapper<K, V>& map_wrapper<K, V>::operator=(const map_wrapper<K, V>& map) {
std::map<K, V>* tmp = this->m;
this->m = new std::map<K, V>(*(map.m));
delete tmp;
return *this;
}
template <class K, class V>
V& map_wrapper<K, V>::operator[](const K& key) {
return (*this->m)[key];
}
template <class K, class V>
const V& map_wrapper<K, V>::operator[](const K& key) const {
return (*this->m)[key];
}
template <class K, class V>
const V& map_wrapper<K, V>::get(const K& key) const {
return (*this->m)[key];
}
template <class K, class V>
void map_wrapper<K, V>::put(const K& key, const V& value) {
(*this->m)[key] = value;
}
template <class K, class V>
int map_wrapper<K, V>::size() const {
return this->m->size();
}
// See : http://www.parashift.com/c++-faq-lite/templates.html#faq-35.15
// [35.15] How can I avoid linker errors with my template classes?
template class __declspec(dllexport) map_wrapper<std::string, int>;
/* End */
__declspec(dllexport) void fun0(map_wrapper<std::string, int>& m) {
std::cout << m["hello"] << std::endl;
}
__declspec(dllexport) void fun1(std::map<std::string, int>& m) {
std::cout << m["hello"] << std::endl;
}
| The KB article you linked is old, it was written before VS2008 came out. It doesn't solve the problem, it is a fundamental limitation of C++. There is no mechanism to verify that classes in separately built binaries have compatible memory layouts and were allocated with the same memory allocator.
Things you can do to avoid the problem:
avoid exporting class objects
build your DLLs and EXE with /MD so they'll share the memory allocator
build all DLLs and EXE with the same compiler and CRT version
carefully control the build settings to ensure they are the same for all projects, project property sheets are the best way to ensure this.
|
2,452,132 | 2,453,300 | Does it ever make sense to make a fundamental (non-pointer) parameter const? | I recently had an exchange with another C++ developer about the following use of const:
void Foo(const int bar);
He felt that using const in this way was good practice.
I argued that it does nothing for the caller of the function (since a copy of the argument was going to be passed, there is no additional guarantee of safety with regard to overwrite). In addition, doing this prevents the implementer of Foo from modifying their private copy of the argument. So, it both mandates and advertises an implementation detail.
Not the end of the world, but certainly not something to be recommended as good practice.
I'm curious as to what others think on this issue.
Edit:
OK, I didn't realize that const-ness of the arguments didn't factor into the signature of the function. So, it is possible to mark the arguments as const in the implementation (.cpp), and not in the header (.h) - and the compiler is fine with that. That being the case, I guess the policy should be the same for making local variables const.
One could make the argument that having different looking signatures in the header and source file would confuse others (as it would have confused me). While I try to follow the Principle of Least Astonishment with whatever I write, I guess it's reasonable to expect developers to recognize this as legal and useful.
| Remember the if(NULL == p) pattern ?
There are a lot of people who will tell a "you must write code like this":
if(NULL == myPointer) { /* etc. */ }
instead of
if(myPointer == NULL) { /* etc. */ }
The rationale is that the first version will protect the coder from code typos like replacing "==" with "=" (because it is forbidden to assign a value to a constant value).
The following can then be considered an extension of this limited if(NULL == p) pattern:
Why const-ing params can be useful for the coder
No matter the type, "const" is a qualifier that I add to say to the compiler that "I don't expect the value to change, so send me a compiler error message should I lie".
For example, this kind of code will show when the compiler can help me:
void bar_const(const int & param) ;
void bar_non_const(int & param) ;
void foo(const int param)
{
const int value = getValue() ;
if(param == 25) { /* Etc. */ } // Ok
if(value == 25) { /* Etc. */ } // Ok
if(param = 25) { /* Etc. */ } // COMPILE ERROR
if(value = 25) { /* Etc. */ } // COMPILE ERROR
bar_const(param) ; // Ok
bar_const(value) ; // Ok
bar_non_const(param) ; // COMPILE ERROR
bar_non_const(value) ; // COMPILE ERROR
// Here, I expect to continue to use "param" and "value" with
// their original values, so having some random code or error
// change it would be a runtime error...
}
In those cases, which can happen either by code typo or some mistake in function call, will be caught by the compiler, which is a good thing.
Why it is not important for the user
It happens that:
void foo(const int param) ;
and:
void foo(int param) ;
have the same signature.
This is a good thing, because, if the function implementer decides a parameter is considered const inside the function, the user should not, and does not need to know it.
This explains why my functions declarations to the users omit the const:
void bar(int param, const char * p) ;
to keep the declaration as clear as possible, while my function definition adds it as much as possible:
void bar(const int param, const char * const p)
{
// etc.
}
to make my code as robust as possible.
Why in the real world, it could break
I was bitten by my pattern, though.
On some broken compiler that will remain anonymous (whose name starts with "Sol" and ends with "aris CC"), the two signatures above can be considered as different (depending on context), and thus, the runtime link will perhaps fail.
As the project was compiled on a Unix platforms too (Linux and Solaris), on those platforms, undefined symbols were left to be resolved at execution, which provoked a runtime error in the middle of the execution of the process.
So, because I had to support the said compiler, I ended polluting even my headers with consted prototypes.
But I still nevertheless consider this pattern of adding const in the function definition a good one.
Note: Sun Microsystems even had the balls to hide their broken mangling with an "it is evil pattern anyway so you should not use it" declaration. see http://docs.oracle.com/cd/E19059-01/stud.9/817-6698/Ch1.Intro.html#71468
One last note
It must be noted that Bjarne Stroustrup seems to be have been opposed to considering void foo(int) the same prototype as void foo(const int):
Not every feature accepted is in my opinion an improvement, though. For example, [...] the rule that void f(T) and void f(const T) denote the same function (proposed by Tom
Plum for C compatibility reasons) [have] the dubious distinction of having been voted into C++ “over my dead body”.
Source: Bjarne Stroustrup
Evolving a language in and for the real world: C++ 1991-2006, 5. Language Features: 1991-1998, p21.
http://www.stroustrup.com/hopl-almost-final.pdf
This is amusing to consider Herb Sutter offers the opposite viewpoint:
Guideline: Avoid const pass-by-value parameters in function declarations. Still make the parameter const in the same function's definition if it won't be modified.
Source: Herb Sutter
Exceptional C++, Item 43: Const-Correctness, p177-178.
|
2,452,278 | 2,452,303 | Problem with memset after an instance of a user defined class is created and a file is opened | I'm having a weird problem with memset, that was something to do with a class I'm creating before it and a file I'm opening in the constructor. The class I'm working with normally reads in an array and transforms it into another array, but that's not important. The class I'm working with is:
#include <vector>
#include <algorithm>
using namespace std;
class PreProcess
{
public:
PreProcess(char* fileName,char* outFileName);
void SortedOrder();
private:
vector< vector<double > > matrix;
void SortRow(vector<double> &row);
char* newFileName;
vector< pair<double,int> > rowSorted;
};
The other functions aren't important, because I've stopped calling them and the problem persists. Essentially I've narrowed it down to my constructor:
PreProcess::PreProcess(char* fileName,char* outFileName):newFileName(outFileName){
ifstream input(fileName);
input.close(); //this statement is inconsequential
}
I also read in the file in my constructor, but I've found that the problem persists if I don't read in the matrix and just open the file. Essentially I've narrowed it down to if I comment out those two lines the memset works properly, otherwise it doesn't.
Now to the context of the problem I'm having with it: I wrote my own simple wrapper class for matrices. It doesn't have much functionality, I just need 2D arrays in the next part of my project and having a class handle everything makes more sense to me.
The header file:
#include <iostream>
using namespace std;
class Matrix{
public:
Matrix(int r,int c);
int &operator()(int i,int j)
{//I know I should check my bounds here
return matrix[i*columns+j];
}
~Matrix();
const void Display();
private:
int *matrix;
const int rows;
const int columns;
};
Driver:
#include "Matrix.h"
#include <string>
using namespace std;
Matrix::Matrix(int r,int c):rows(r),columns(c)
{
matrix=new int[rows*columns];
memset(matrix,0,sizeof(matrix));
}
const void Matrix::Display(){
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++)
cout << (*this)(i,j) << " ";
cout << endl;
}
}
Matrix::~Matrix()
{
delete matrix;
}
My main program runs:
PreProcess test1(argv[1],argv[2]);
//test1.SortedOrder();
Matrix test(10,10);
test.Display();
And when I run this with the input line uncommented I get:
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 -1371727776 32698 -1 0
0 0 0 0 6332656 0 -1 -1 0 0
6332672 0 0 0 0 0 0 0 0 0
0 0 0 0 -1371732704 32698 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
I really don't have a clue what's going on in memory to cause this, on a side note if I replace memset with:
for(int i=0;i<rows*columns;i++)
*(matrix+i) &= 0x0;
Then it works perfectly, it also works if I don't open the file. If it helps I'm running GCC 64-bit version 4.2.4 on Ubuntu.I assume there's some functionality of memset that I'm not properly understanding.
| You use memset() like this:
memset(matrix,0,sizeof(matrix));
Here matrix is a pointer, so sizeof(matrix) gives the size of a pointer, not the size of the array. To fill the whole array, use columns * rows * sizeof(int) instead.
|
2,452,283 | 2,452,392 | Turn off the warnings due to boost library | I am building an application in C++, Mac OS X, Qt and using boost libraries. Every time I build a project I get a huge list of warnings only from boost libraries itself.
How to turn them off, so that I can see only my project specific warnings and errors?
| Use -isystem instead of -I to add Boost headers to include path. This option means to treat headers found there as system headers, and suppress warnings originating there.
|
2,452,393 | 2,452,501 | std::iostream link error vs2010 rc1 | I'm converting a project from vs2008 to vs2010 and getting linker errors for std:ifstream/ofstream
error LNK2001: unresolved external symbol "__declspec(dllimport) public: bool __thiscall std::basic_ofstream<char,struct std::char_traits<char> >::is_open(void)const " (__imp_?is_open@?$basic_ofstream@DU?$char_traits@D@std@@@std@@QBE_NXZ)
Building static (/MT) or dll (/MD) with unicode or standard and release/debug gives the same error.
Manually adding libcpmtd.lib (static) or msvcprtd.lib (dll) to the linker doesn't help.
Has anyone else seen this?
| If you don't get an answer for this particular problem, there is a brute force approach that I've used with great success:
Using Visual Studio 2010, create a new project of the same type in a temporary folder somewhere (use the same project and solution name), and make sure you use the same options as your VS2008 project.
At this point, you may simply be able to compare the new VS2010 project file against your existing VS2008 project's file using a visual diff tool (I like BeyondCompare). The project files are XML, so it's fairly easy to visually compare them. From this comparison, I can usually tell what libraries and other options need to change.
If the older project file has too many changes (making the comparison difficult), repeat the above steps (using VS2008 this time) to create another plain-jane project, writing it to a different temporary location.
Now you should be able to compare the VS2008 and VS2010 boilerplate project files to see what comple and link settings are different.
|
2,452,398 | 2,452,466 | Splash screen in Windows | How can I display a splash screen using C or C++ in Windows? What libraries or Windows components would be applicable?
| Try to create a window with the createwindowex function and use the style (dwStyle) WS_POPUP.
You can read about CreateWindowEx here.
|
2,452,457 | 2,452,511 | Network file transfer in Windows | I want to transfer files across the network using C or C++. What topics should I look up? How can I do this?
| While you could use ReadFile to read the file's contents and then send it over a socket, Windows also provides the TransmitFile API to enable you to read a file's data and send it over a socket with one system call.
|
2,452,476 | 2,452,494 | Auto-Update for a Windows application | Is there an open source project that allows for an auto-update of windows binaries? The Luau update library is very similar to what I'm looking for but it was abandoned in 2005.
| Google Omaha . But I have not tried it and don't know how easy it is to use.
|
2,452,510 | 2,452,556 | Doesn't the Visual Studio 2008 compiler autocast to double with sqrt in C++? | Shouldn't the compiler automatically cast to a double in the following? At least according to Walter Savitch.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int k;
for(k = 1; k <= 10; k++)
cout << "The square root of k is: " << sqrt(k) << endl;
return 0;
}//error C2668: 'sqrt' : ambiguous call to overloaded function
//Visual Studio 2008 on Win Vista
| The problem is that there are three versions of sqrt to choose from:
double sqrt ( double x );
float sqrt ( float x );
long double sqrt ( long double x );
Since you're passing in an int, the compiler is going to promote your argument but it's equally valid to promote your integer to any of the above types, so it's ambiguous.
You can fix this by simply explicitly casting to one of the above types, as in:
cout << "The square root of k is: " << sqrt((double)k) << endl;
|
2,452,561 | 2,494,462 | OutputDebugString + DebugView = not tabs! | I am dumping \t delimited data using using OutputDebugString and then use ex-Sysinternals DebugView to capture it.
The problem is that all the data in DebugView appear to be space delimited, hence I need to perfrorm CTRL+H "\x20" "t" to replace spaces with the tabs before I can use it (I really need tab delimited data).
Is there anyway to tell DebugView not to replace tabs with spaces?
Or maybe there is a better tool available to capture output of the OutputDebugString function?
Any ideas are very welcome!
| It seems this is a "feature" in DebugView. I have tried with Hoo Wintail and this dude collects tabs without any problem. So I see 3 solutions:
You get Hoo Wintail (highly recommended)
You write your on tool (look here for some idea how to do it or even get a complete one)
You redirect to file.
I strongly vote for option 1.
|
2,452,576 | 2,452,596 | Run process in .NET and C++ | I search for the function that run programm by path, and working of main programm is stopped until run second programm. Can i do that by using System.Diagnostics.Process class?
| look at this question
Use this if you want to just use the win32 api
#include <stdio.h>
#include <Windows.h>
int main(int argc, char ** argv)
{
STARTUPINFO SI;
PROCESS_INFORMATION PI;
memset(&SI,0,sizeof(SI));
memset(&PI,0,sizeof(PI));
SI.cb = sizeof(SI);
//ProcessorCap
if(!CreateProcess(NULL,"Notepad.exe ",NULL,NULL,false,0,NULL,NULL,&SI,&PI))
{
printf("Error %d",GetLastError());
return 1;
}
DWORD ExitCode;
do
{
GetExitCodeProcess(PI.hProcess,&ExitCode);
Sleep(100);
}while (ExitCode == STILL_ACTIVE);
printf("Exited");
}
|
2,452,728 | 2,452,787 | Is it a good design to return value by parameter? | bool is_something_ok(int param,SomeStruct* p)
{
bool is_ok = false;
// check if is_ok
if(is_ok)
// set p to some valid value
else
// set p to NULL
return is_ok;
}
this function return true and set p to a valid value if "something is ok"
otherwise return false and set p to NULL
Is that a good or bad design? personally, i feel uncomfortable when i use it.
If there is no document and comment, i really don know how to use it.
BTW:Is there some authoritative book/article about API design?
| Since you have tagged the question as C++ and not C, I would suggest you to:
return the value directly
if you have more than one value, use output parameters
use non-const references as output parameter where possible (instead of pointers), and use const-references for the input parameters.
if something went wrong, raise a exception instead of returning false or -1.
But that are just some general hints. The best way to go always depends on the specific problem...
|
2,452,872 | 2,453,481 | Visual C++ 9 compiler options to make the program run faster | I have built an open-source application from the source code. Unfortunately, the original executable runs significantly faster. I tried to enable few compiler optimizations, but the result wasn't satisfactory enough. What else do I need to make in Visual Studio 2008 to increase the executable performance?
Thanks!
| Basically try enabling everything under Optimisation in project settings, then ensure Link Time Code Generation is on, enable Function-level linking and full COMDAT folding (that only reduces the size of the EXE but could help with caching), and turn off security features such as by defining _SECURE_SCL=0. Remember some of these settings have other implications, especially the security ones.
|
2,452,880 | 2,452,928 | What is the best and useful debug tool in Linux environment for Perl and C++ scripts? | What is the best and useful debug tool in Linux environment for Perl and C++ scripts?
In related to that, does anyone know the differences between Eclipse to DDD tools?
Thank you,
YoDar.
| Sorry, I don't do Perl.
But I do Eclipse & DDD.
Eclipse is an IDE (which also supports Perl). IF you use C/C++, for instance, it supports the GDB. If you can compile Perl, it will probably support that too, which means that you can step through your code, line by line, examining the call stack, looking at variables, changing their values, etc.
DDD is a front-end for GDB, so it can do all of that debugging stuff, but it is not an IDE that will let you edit & compile your code.
Generally, Eclipse is more than good enough, but when I get into complicated lists or structures with lots of pointers, I love DDD for this single picture - which speaks ten thousand words ...
From http://www.gnu.org/software/ddd/all.png
|
2,453,048 | 2,455,729 | How can i hold reference in boost::shared_ptr using boost::bind without definition of explicit function? | I want to hold reference to object so it doesn't get deleted in bind function, but without using helper function.
struct Int
{
int *_int;
~Int(){ delete _int; }
};
void holdReference(boost::shared_ptr<Int>, int*) {} // helper
boost::shared_ptr<int> fun()
{
boost::shared_ptr<Int> a ( new Int );
// I get 'a' from some please else, and want to convert it
a->_int = new int;
return boost::shared<int>( a->_int, boost::bind(&holdReference, a, _1) );
}
Is there a way to declare holdReference function in place? Like with lambda expressions or sth? (without using this nasty holdReference function, that have to be declared outside the scope of fun function)
I had few tries but non of them compiled :)
Ok, here is more detailed example:
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
// the case looks more or less like this
// this class is in some dll an I don't want to use this class all over my project
// and also avoid coppying the buffer
class String_that_I_dont_have
{
char * _data; // this is initialized in 3rd party, and released by their shared pointer
public:
char * data() { return _data; }
};
// this function I created just to hold reference to String_that_I_dont_have class
// so it doesn't get deleted, I want to get rid of this
void holdReferenceTo3rdPartyStringSharedPtr( boost::shared_ptr<String_that_I_dont_have>, char *) {}
// so I want to use shared pointer to char which I use quite often
boost::shared_ptr<char> convert_function( boost::shared_ptr<String_that_I_dont_have> other)
// 3rd party is using their own shared pointers,
// not the boost's ones, but for the sake of the example ...
{
return boost::shared_ptr<char>(
other->data(),
boost::bind(
/* some in place here instead of holdReference... */
&holdReferenceTo3rdPartyStringSharedPtr ,
other,
_1
)
);
}
int main(int, char*[]) { /* it compiles now */ }
// I'm just looking for more elegant solution, for declaring the function in place
| You may be looking for the "shared ownership" constructor, this allows ref counting an interior pointer.
struct Int
{
int *_int;
~Int(){ delete _int; }
};
boost::shared_ptr<int> fun()
{
boost::shared_ptr<Int> a (new Int);
a->_int = new int;
// refcount on the 'a' instance but expose the interior _int pointer
return boost::shared_ptr<int>(a, a->_int);
}
|
2,453,189 | 2,453,212 | How to produce 64 bit masks? | Based on the following simple program the bitwise left shift operator works only for 32 bits. Is it true?
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
long long currentTrafficTypeValueDec;
int input;
cout << "Enter input:" << endl;
cin >> input;
currentTrafficTypeValueDec = 1 << (input - 1);
cout << currentTrafficTypeValueDec << endl;
cout << (1 << (input - 1)) << endl;
return 0;
}
The output of the program:
Enter input:
30
536870912
536870912
Enter input:
62
536870912
536870912
How could I produce 64-bit masks?
| Make input an long long too, and use 1LL << (input - 1LL). Here your shift is computed on 32 bits, and converted to 64 bits when stored in currentTrafficTypeValueDec.
|
2,453,191 | 2,453,260 | How get Win32_OperatingSystem.LastBootUpTime in datetime format | I have been trying to get LastBootUpTime using Win32_OperatingSystem class (WMI).
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
VARIANT vtProp;
// Get the value of the Name property
hr = pclsObj->Get(L"LastBootUpTime", 0, &vtProp, 0, 0);
VariantClear(&vtProp);
I want to write this time to CTime or COleDateTime variable. But variable vtProp has BSTR type and look like 20100302185848.499768+300
Also any datetime property of any WMI class have BSTR type
How can I put datetime property of WMI class to CTime?
But how use SWbemDateTime.GetVarDate() in C++? In MSDN just scripting sample for this function
| You'll have to do some parsing to convert it. The format is yyyyMMddhhmmss.ffffff+zzz (zzz is UTC offset in minutes). The SWbemDateTime.GetVarDate() method can do it for you.
|
2,453,225 | 2,453,388 | Is there any need for me to use wstring in the following case | Currently, I am developing an app for a China customer. China customer are mostly switch to GB2312 language in their OS encoding. I need to write a text file, which will be encoded using GB2312.
I use std::ofstream file
I compile my application under MBCS mode, not unicode.
I use the following code, to convert CString to std::string, and write it to file using ofstream
std::string Utils::ToString(CString& cString) {
/* Will not work correctly, if we are compiled under unicode mode. */
return (LPCTSTR)cString;
}
To my surprise. It just works. I thought I need to at least make use of wstring. I try to do some investigation.
Here is the MBCS.txt generated.
alt text http://sites.google.com/site/yanchengcheok/Home/stackoverflow0.PNG
I try to print a single character named 脚 (its value is 0xBDC5)
When I use CString to carry this character, its length is 2.
When I use Utils::ToString to perform conversion to std::string, the returned string length is 2.
I write to file using std::ofstream
My question is :
When I exam MBCS.txt using a hex editor, the value is displayed as BD (LSB) and C5 (MSB). But I am using little endian machine. Isn't hex editor should show me C5 (LSB) and BD (MSB)? I check from wikipedia. GB2312 seems doesn't specific endianness.
It seems that using std::string + CString just work fine for my case. May I know in what case, the above methodology will not work? and when I should start to use wstring?
| About 1. Endianness is a problem you meet when you serialize a unit in term of smaller units (i.e. serialize seizets in term of octets). I'm far from being a specialist of CJK encodings, but it seems to me that GB2112 is a coded character set which can be used with several encoding schemes. The encoding schemes cited in the wikipedia page as being used for GB2112 (ISO 2022, EUC-CN and HZ) are all defined in terms of octets. So there is no endianness issue if serialized as octets.
Contrast this with Unicode encoding schemes: UTF-8 is defined in terms of octets and has no endianness issue when serialized as octets, UTF-16 is defined in terms of seizets and if serialized as octets endianness must be specified, UTF-32 is defined in terms of 32 bits units and if serialized as octets endianness must be specified.
|
2,453,318 | 2,459,031 | Get application icon from ProcessSerialNumber | I would like to get the application icon for all foreground applications running on my Mac. I'm already iterating over all applications using the Process Manager API. I have determined that any process that does not have the modeBackgroundOnly flag set in the processMode (as retrieved from GetProcessInformation()) is a "foreground" application, and shows up in the task switcher window.
All I need is an API that gives me a CImageRef (or similar) that contains the application icon for a process. I'm free to use either carbon or cocoa APIs.
| On Mac OS X 10.6 or later, you can ask a running application for its icon.
On earlier versions of Mac OS X, you'll have to get it by looking at the application's bundle. Pass the PSN to the GetProcessBundleLocation function to get the bundle's location as an FSRef, then pass that to the GetIconRefFromFileInfo function.
|
2,453,367 | 2,453,489 | Abstract base class puzzle | In my class design I ran into the following problem:
class MyData
{
int foo;
};
class AbstraktA
{
public:
virtual void A() = 0;
};
class AbstraktB : public AbstraktA
{
public:
virtual void B() = 0;
};
template<class T>
class ImplA : public AbstraktA
{
public:
void A(){ cout << "ImplA A()"; }
};
class ImplB : public ImplA<MyData>, public AbstraktB
{
public:
void B(){ cout << "ImplB B()"; }
};
void TestAbstrakt()
{
AbstraktB *b = (AbstraktB *) new ImplB;
b->A();
b->B();
};
The problem with the code above is that the compiler will complain that AbstraktA::A() is not defined.
Interface A is shared by multiple objects. But the implementation of A is dependent on the template argument. Interface B is the seen by the outside world, and needs to be abstrakt.
The reason I would like this is that it would allow me to define object C like this:
Define the interface C inheriting from abstrakt A.
Define the implementation of C using a different datatype for template A.
I hope I'm clear. Is there any way to do this, or do I need to rethink my design?
| You have two paths of inheritance from AbstracktA, you implement AbstraktA::A() only in one of them, so the compiler complains.
You probably want to inherit virtually from AbstraktA in both case so that there is only one AbstraktA base object (add virtual before AbstraktA).
|
2,453,399 | 2,577,475 | How to make Visual C++ 9 not emit code that is actually never called? | My native C++ COM component uses ATL. In DllRegisterServer() I call CComModule::RegisterServer():
STDAPI DllRegisterServer()
{
return _Module.RegisterServer(FALSE); // <<< notice FALSE here
}
FALSE is passed to indicate to not register the type library.
ATL is available as sources, so I in fact compile the implementation of CComModule::RegisterServer(). Somewhere down the call stack there's an if statement:
if( doRegisterTypeLibrary ) { //<< FALSE goes here
// do some stuff, then call RegisterTypeLib()
}
The compiler sees all of the above code and so it can see that in fact the if condition is always false, yet when I inspect the linker progress messages I see that the reference to RegisterTypeLib() is still there, so the if statement is not eliminated.
Can I make Visual C++ 9 perform better static analysis and actually see that some code is never called and not emit that code?
| Turns out the key is to enable link-time code generator all the way through the compiler settings.
It must be enabled on the General tab - Whole program optimization must be set to "Use link-time code generation". It must also be enabled on the C++ -> Optimization tab - "Whole program optimization* must be set to "Enable link-time code generation". It must also be enabled on the Linker -> Optimization tab - Link Time Code Generation must be set to "Use Link Time Code Generation". Then /OPT:REF and /OPT:ICF (again, *Linker -> Optimization" tab) must both be enabled.
And this effectively removes the calls to RegisterTypeLib() - it is no longer in the list of symbols imported.
|
2,453,417 | 2,469,118 | LsaCallAuthenticationPackage returns ERROR_INVALID_PARAMETER 87 (0x57) when trying to purge a specific ticket | I'm trying to purge a specific ticket from the cache,using LsaCallAuthenticationPackage.
I always get ERROR_INVALID_PARAMETER 87 in the package status.
What could be the reason?
Here is my code (All other steps succeeded):
KERB_QUERY_TKT_CACHE_REQUEST tktCacheRequest = {
KerbQueryTicketCacheMessage};
void* pRep;
DWORD cbRep;
NTSTATUS pkgStatus;
NTSTATUS s = LsaCallAuthenticationPackage(
* hLsa, * nAuthPackage,
&tktCacheRequest, sizeof tktCacheRequest,
&pRep, &cbRep, &pkgStatus);
pTktCacheResponse = (KERB_QUERY_TKT_CACHE_RESPONSE)pRep;
for (ULONG i = 0; i < pTktCacheResponse->CountOfTickets; ++i)
{
KERB_TICKET_CACHE_INFO& ti = pTktCacheResponse->Tickets[i];
if (/Some condition/)
{
KERB_PURGE_TKT_CACHE_REQUEST req;
req.MessageType = KerbPurgeTicketCacheMessage;
req.ServerName = ti.ServerName;
req.RealmName = ti.ServerName;
req.LogonId.HighPart = req.LogonId.LowPart = 0;
NTSTATUS pkgStatus = 0;
PVOID pReturnBuffer = NULL;
ULONG nReturnedBufferLen = 0;
NTSTATUS s = LsaCallAuthenticationPackage(
hLsa, nAuthPackage,
&req, sizeof (req) *2,
0, 0, &pkgStatus);
ULONG winErr = LsaNtStatusToWinError(pkgStatus);
}
}
Thanks!!
| I kust use the memory allocation model as in the original Microsoft's klist (found in Microsoft Windows Platform SDK's samples), and got it works.
Thanks.
|
2,453,425 | 2,453,456 | How can i sort a map by its .second parameter | If i have a stl map from string to int and i want to print all the int values sorted - how can i do that?
| You cannot sort a map by its values due to the implementation of the map.
If you want to emit the elements in the map in such a sorted order then you have to first dump the map contents into a vector (say) and sort that vector:
template <typename T1, typename T2>
struct less_second {
typedef pair<T1, T2> type;
bool operator ()(type const& a, type const& b) const {
return a.second < b.second;
}
};
map<string, int> mymap;
// …
vector<pair<string, int> > mapcopy(mymap.begin(), mymap.end());
sort(mapcopy.begin(), mapcopy.end(), less_second<string, int>());
Or alternatively, just copy the values from the map, leaving the keys, and sort the resulting vector directly.
|
2,453,476 | 2,453,519 | To catch or not to catch | Should application catch "bad" signals such as SIGSEV, SIGBUS?
| Those signals are produced in "should never happen" circumstances, when your program is in an undefined state. If you did catch them, continuing execution would be extremely problemeatic, as it would almost certainly cause more, possibly even more severe, errors. Also, if you don't catch them, the OS may be able to do things like produce useful diagnostics such as core dumps. So I would say "no", unless you don't want the core dump, and your error handling does something very simple such as write to a log and terminate.
|
2,453,865 | 2,453,913 | why Floating point exception? | I have a floating point exception, and I don't know why.
the code is this:
void calcola_fitness(){
vector<double> fitness;
int n=nodes.size();
int e=edges.size();
int dim=feasibility.size();
int feas=(feasibility[dim-1])*100;
int narchi=numarchicoll[dim-1]/e;
int numero_nodi=freePathNode.size()/n;
double dist_start_goal=node_dist(0,1);
int i,f,t;
double pathlenght=0;
int siize=freePathNode.size();
for(i=0;i!=siize-1; i++){
f=freePathNode[i].getIndex();
i++;
t=freePathNode[i].getIndex();
i--;
pathlenght=pathlenght+node_dist(f,t);
}
double pathlenghtnorm=pathlenght/10*dist_start_goal;
double fit=((double)numero_nodi+pathlenghtnorm+(double)narchi)*((double)feas);
fitness.push_back(fit);
}
Could anybody help me? What's the problem? I could I solve this?
thank you very much
| "Floating point exception" (SIGFPE) is actually a misnomer. Any kinds of arithmetics exception will trigger SIGFPE. This includes divide-by-zero.
You should check if nodes and edges are empty.
|
2,453,867 | 2,453,884 | GCC problem: in template | i have redhat with gcc 4.1.1 i have compile as "gcc test.c" and give the following error
Error : expected '=' ,',' , ';' , ásm' or '__ attribute__' before '<' token
the code in "test.c" is as follow
template <typename T> class A {
public:
T foo;
};
| This is C++ code, not C. You need to use g++, i.e. g++ test.c. Also, to avoid confusion, you should rename your file to end with .cpp or .cxx.
|
2,454,019 | 2,454,082 | Why aren't static const floats allowed? | I have a class which is essentially just holds a bunch of constant definitions used through my application. For some reason though, longs compile but floats do not:
class MY_CONSTS
{
public :
static const long LONG_CONST = 1; // Compiles
static const float FLOAT_CONST = 0.001f; // C2864
};
Gives the following error:
1>c:\projects\myproject\Constant_definitions.h(71) : error C2864: 'MY_CONSTS::FLOAT_CONST' : only static const integral data members can be initialized within a class
Am I missing something?
| To answer the actual question you asked: "because the standard says so".
Only variables of static, constant, integral types (including enumerations) may be initialized inside of a class declaration. If a compiler supports in-line initialization of floats, it is an extension. As others pointed out, the way to deal with static, constant, non-integral variables is to define and initialize them in the class's corresponding source file (not the header).
C++ Standard Section 9.2 "Class Members" item 4:
A member-declarator can contain a
constant-initializer only if it declares a static member (9.4) of
const integral or const enumeration
type, see 9.4.2.
Section 9.4.2 "Static Data Members" item 2:
If a static data member is of const
integral or const enumeration type,
its declaration in the class definition
can specify a constant-initializer
which shall be an integral constant
expression (5.19). In that case, the
member can appear in integral constant
expressions. The member shall still be
defined in a namespace scope if it is
used in the program and the namespace
scope definition shall not contain an
initializer.
|
2,454,483 | 2,454,754 | inserting std::strings in to a std::map | I have a program that reads data from a file line-by-line. I would like to copy some substring of that line in to a map as below:
std::map< DWORD, std::string > my_map;
DWORD index; // populated with some data
char buffer[ 1024 ]; // populated with some data
char* element_begin; // points to some location in buffer
char* element_end; // points to some location in buffer > element_begin
my_map.insert( std::make_pair( index, std::string( element_begin, element_end ) ) );
This std::map<>::insert() operation takes a long time (It doubles the file parsing time). Is there a way to make this a less expensive operation?
Thanks,
PaulH
Edit: to be more specific, I want to know that I'm doing the minimum number of copy operations to get the data from the file in to the map.
| To answer your supplementary question slightly. Try changing the map temporarily to a vector of strings, and then time it inserting a fixed string value into the vector For example:
vector <string> v;
string s( "foobar" );
your insert loop:
v.push_back( s );
That should give you a lower bound of what is possible regarding speed.
Also, you should time things with all optimisations turned on (if you are not already doing so). This can make a suprising difference to many Standard Library operations.
|
2,454,817 | 2,455,080 | error C2784: Could not deduce template argument | Still fighting with templates. In this example, despite the fact that is copied straight from a book I'm getting the following error message: Error 2 error C2784: 'IsClassT<T>::One IsClassT<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'.
This is an example from a book Templates - The Complete Guide.
(I work with Visual Studio 2010 RC).
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
template<typename C> static Two test(…);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
class MyClass {
};
struct MyStruct {
};
union MyUnion {
};
void myfunc()
{
}
enum E {e1} e;
// check by passing type as template argument
template <typename T>
void check()
{
if (IsClassT<T>::Yes) {
std::cout << " IsClassT " << std::endl;
}
else {
std::cout << " !IsClassT " << std::endl;
}
}
// check by passing type as function call argument
template <typename T>
void checkT (T)
{
check<T>();
}
int main()
{
/*std::cout << "int: ";
check<int>(); */
std::cout << "MyClass: ";
check<MyClass>();
}
And although I know roughly what's going on in this example I cannot fix this error.
Thanks for help.
| My compiler (MSVC2008TS) likes it if you don't fully qualify the test expression:
enum { Yes = sizeof(test<T>(0)) == 1 };
But is this even legal code?
|
2,454,871 | 2,455,014 | Is there a library for editing program flow? | I was wondering if there is a library for editing program flow. I refer to conditions if, loops (do, while, for) and other elements that can exist inside a program.
What I would like to have is some sort of a CAD application (similar to an UML editor) from where I can take some elements and edit their properties, make connections between them.
Do you know similar software that does this, or resembles a little what I'm trying to achieve?
Thanks,
Iulian
PS: It is something that should resemble this image.
PS2: I want to write code for doing this, I was wondering if such things exist.
| A short advice.
Programming languages were actually invented to describe program flows...
It is possible to draw flows, but as the notation is much less powerful, you will find that it will become easy to design trivial or simple flows, and impossible to design even moderatly complex flows.
Phrased in another way; A complex* problem will not become less complex because you are using a tool with limited functionality.
(Which is exactly the wishful thinking thats makes BPEL [JBMP et al] utter boulderdash.)
|
2,454,905 | 2,458,547 | Force type of C++ template | I've a basic template class, but I'd like to restrain the type of the specialisation to a set of classes or types. e.g.:
template <typename T>
class MyClass
{
.../...
private:
T* _p;
};
MyClass<std::string> a; // OK
MYCLass<short> b; // OK
MyClass<double> c; // not OK
Those are just examples, the allowed types may vary.
Is that even possible? If it is, how to do so?
Thanks.
| Another version is to leave it undefined for the forbidden types
template<typename T>
struct Allowed; // undefined for bad types!
template<> struct Allowed<std::string> { };
template<> struct Allowed<short> { };
template<typename T>
struct MyClass : private Allowed<T> {
// ...
};
MyClass<double> m; // nono
|
2,455,071 | 2,455,638 | Validating document in Xerces C++ | I want to load an XML document in Xerces-C++ (version 2.8, under Linux), and validate it using a DTD schema not referenced from the document. I tried the following:
XercesDOMParser parser;
parser.loadGrammar("grammar.dtd", Grammar::DTDGrammarType);
parser.setValidationScheme(XercesDOMParser::Val_Always);
parser.parse("xmlfile.xml");
But it doesn't indicate an error if the document is not valid. What am I missing?
| You'll need to set an error handler before calling parse if you want to see anything:
Handler handler;
parser.setErrorHandler( &handler );
where Handler is a class derived from ErrorHandler
|
2,455,146 | 2,455,364 | MapViewOfFile shared between 32bit and 64bit processes | I'm trying to use MapViewOfFile in a 64 bit process on a file that is already mapped to memory of another 32 bit process. It fails and gives me an "access denied" error. Is this a known Windows limitation or am I doing something wrong? Same code works fine with 2 32bit processes.
The code sort of looks like this:
hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szShmName);
if (NULL == hMapFile)
{ /* failed to open - create new (this happens in the 32 bit app) */
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;
/* give access to members of administrators group */
BOOL success = ConvertStringSecurityDescriptorToSecurityDescriptor(
"D:(A;OICI;GA;;;BA)",
SDDL_REVISION_1,
&(sa.lpSecurityDescriptor),
NULL);
HANDLE hShmFile = CreateFile(FILE_XXX_SHM,
FILE_ALL_ACCESS, 0,
&sa,
OPEN_ALWAYS, 0, NULL);
hMapFile = CreateFileMapping(hShmFile, &sa, PAGE_READWRITE,
0,
SHM_SIZE,
szShmName);
CloseHandle(hShmFile);
}
// this one fails in 64 bit app
pShm = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, SHM_SIZE);
| When you call CreateFile in the 32-bit application, you're passing 0 for the sharing parameter, which means no sharing is allowed. Changing that to FILE_SHARE_READ | FiLE_SHARE_WRITE would probably be a step in the right direction.
Edit: I just whipped together a demo that works (at least for me):
#include <windows.h>
#include <iostream>
static const char map_name[] = "FileMapping1";
static const char event1_name[] = "EventName1";
static const char event2_name[] = "EventName2";
int main() {
HANDLE mapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, map_name);
if (NULL == mapping) {
std::cout << "Calling CreateFile\n";
HANDLE file = CreateFile("MappedFile",
FILE_ALL_ACCESS,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
0,
NULL);
std::cout << "Creating File mapping\n";
mapping = CreateFileMapping(file, NULL, PAGE_READWRITE, 0, 65536, map_name);
std::cout << "Closing file handle\n";
CloseHandle(file);
}
std::cout << "Mapping view of file\n";
char *memory = (char *)MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 65536);
if (memory == NULL) {
std::cerr << "Mapping Failed.\n";
return 1;
}
std::cout << "Mapping succeeded\n";
HANDLE event = CreateEvent(NULL, false, false, event1_name);
if (GetLastError()==ERROR_ALREADY_EXISTS) {
std::cout <<"Waiting to receive string:\n";
WaitForSingleObject(event, INFINITE);
std::cout << "Received: " << memory;
HANDLE event2 = CreateEvent(NULL, false, false, event2_name);
SetEvent(event2);
}
else {
char string[] = "This is the shared string";
std::cout << "Sending string: " << string << "\n";
strncpy(memory, string, sizeof(string));
SetEvent(event);
HANDLE event2 = CreateEvent(NULL, false, false, event2_name);
WaitForSingleObject(event2, INFINITE);
}
return 0;
}
Any combination of 32- or 64-bit executables seems to work fine.
Edit2: Note, however, that this is purely demo-level code. Just for example, the name of each shared object should normally contain a GUID-string to ensure against accidental collision with other programs. I've also skipped quite a bit of error checking, not to mention the minor detail that this code doesn't accomplish anything useful.
|
2,455,216 | 2,455,323 | Are pointers primitive types in C++? | I was wondering about the last constructor for std::string mentioned here. It says:
template<class InputIterator> string (InputIterator begin, InputIterator end);
If InputIterator is an integral type, behaves as the sixth constructor version (the one right above this) by typecasting begin and end to call it:
string(static_cast<size_t>(begin),static_cast<char>(end));
In any other case, the parameters are taken as iterators, and the content is initialized with the values of the elements that go from the element referred by iterator begin to the element right before the one referred by iterator end.
So what does that mean if InputIterator is a char * ?
EDIT: Ok, my bad. I just realized that it says integral type, not primitive type in the documentation, so the question does not apply to that example. But still, are pointers primitives?
| C++ doesn't have a concept of "primitive" types; integers are fundamental types and pointers are compound types.
In this case, char* can't be converted into either size_t or char, so it will be taken as the InputIterator template parameter.
|
2,455,371 | 2,455,525 | How to implement a private virtual function within derived classes? | I know why I want to use private virtual functions, but how exactly can I implement them?
For example:
class Base{
[...]
private:
virtual void func() = 0;
[...]
};
class Derived1: public Base{
void func()
{ //short implementation is ok here
}
};
class Derived2: public Base{
void func(); //long implementation elsewhere (in cpp file)
};
[...]
void Derived2::func()
{ //long implementation
}
The first version is ok but not always possible.
Isn't the second version simply name hiding? How do you define the Base::func() of Derived2, if you cannot do it within the class declaration of Dereived2?
Thanks
|
How do you define the Base::func() of Derived2, if you cannot do it within the class declaration of Dereived2?
You don't define "Base::func() of Derived2" (whatever this might be), you define Derived2::func(). This compiles just fine for me:
#include <iostream>
class Base{
private:
virtual void foo() = 0;
public:
void bar() {foo();}
};
class Derived: public Base{
void foo();
};
void Derived::foo()
{
std::cout << "inside of 'Derived1::foo()'\n";
}
int main()
{
Derived d;
Base& b = d;
b.bar();
return 0;
}
What's your problem with it?
|
2,455,403 | 2,456,482 | How visual studio intellisense recognize functions and properties in classes even though there is no reflection in C++? | I want to list properties and functions present in c++ classes. Is that functionality already implemented in any library ? Does visual studio intellisense use any library ? Is that library available publicly from Microsoft?
| The Visual C++ team maintains a blog that has had several very nice articles about how IntelliSense has worked in the past and how it will work in the future:
IntelliSense History, Part 1
IntelliSense, Part 2 (The Future)
Visual C++ Code Model
Rebuilding Intellisense
Visual C++ Code Model in Visual Studio 2010
Essentially they build their own 'reflection' database (the .ncb file in current and past version sof VS, using a compact SQL database starting with VS2010) by parsing the headers and other source files - using both custom parsers and parsing that's done with the cooperation of the compiler.
Apparently at least some of that information is available in the VCCodeModel and related interfaces that the Visual Studio extensibility model provides. I have no idea how well the extensibility model works or how easy it is to use.
|
2,455,806 | 2,456,756 | Unsigned long with negative value | Please see the simple code below:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
unsigned long currentTrafficTypeValueDec;
long input;
input=63;
currentTrafficTypeValueDec = (unsigned long) 1LL << input;
cout << currentTrafficTypeValueDec << endl;
printf("%u \n", currentTrafficTypeValueDec);
printf("%ld \n", currentTrafficTypeValueDec);
return 0;
}
Why printf() displays the currentTrafficTypeValueDec (unsigned long) with negative value?
The output is:
9223372036854775808
0
-9223372036854775808
| Fun with bits...
cout is printing the number as an Unsigned Long, all 64 bits are significant and print as unsigned binary integer (I think the format here would be %lu).
printf(%u ... treats the input as an normal unsigned integer (32 bits?). This causes bits 33 through 64 to drop off - leaving zero.
printf(%ld ... treats the input as a 64 bit signed number and just prints it out as such.
The thing you might find confusing about the last printf is that it gives the same absolute value as cout, but with a minus sign. When viewing as an unsigned integer all 64 bits are significant in producing the integer value. However for signed numbers, bit 64 is the sign bit. When the sign bit is set (as it is in your example) it indicates the remaining 63 bits are to be treated as a negative number represented in 2's compliment. Positive numbers are printed simply by converting their binary value to decimal. However for a negative number the following happens: Print a negative sign, XOR bits 1 through 63 with binary '1' bits, add 1 to the result and print the unsigned value. By dropping the sign bit (bit 64) you end up with 63 '0' bits, XORing with '1' bits gives you 63 '1' bits, add +1 and the whole thing rolls over to give you an unsigned integer having bit 64 set to '1' and the rest set to '0' - which is the same thing you got with cout BUT, as a negative number.
Once you have worked out why the above explanation is correct you should also be able to make sense out of this
|
2,456,308 | 2,456,350 | Recursion with an Array; can't get the right value to return | Solution found - in under 5 minutes, thanks folks!
Clarification: The contents of my array are the values 0-29. So array[0][0] = 0, while array[29][0] = 29 --- they're just test values. Also, I have a potential solution that's been posted multiple times, going to try that.
Recursive Solution: Not working!
Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The IF section (time == 0) provides a base case where the recursion should terminate, returning 0. The ELSE section is where the recursive call occurs: total is a private variable defined in the header file, elsewhere. It's initialized to 0 in a constructor, elsewhere. The function calls itself, recursively, adding productsAndSales[time-1][0] to total, again, and again, until the base call. Then the total is returned, and printed out later. Well, that's what I hoped for anyway.
What I imagined would happen is that I would add up all the values in this one column of the array and the value would get returned, and printed out. Instead if returns 0. If I set the IF section to "return 1", I noticed that it returns powers of 2, for whatever value time is. EG: Time = 3, it returns 2*2 + 1. If time = 5, it returns 2*2*2*2 + 1.
I don't understand why it's not returning the value I'm expecting. One thing I thought of is that I'm attempting to use private variable total in the return section, along with the recursive call...maybe that's a no-no somehow?
int CompanySales::calcTotals( int time )
{
cout << setw( 4 );
if ( time == 0 )
{
return 0;
}
else
{
return total += calcTotals( productsAndSales[ time-1 ][ 0 ]);
}
}
Iterative Solution: Working!
Explanation: An integer, time, is passed into the function. It's then used to provide an end to the FOR statement (counter<time). The FOR statement cycles through an array, adding all of the values in one column together. The value is then returned (and elsewhere in the program, printed out). Works perfectly.
int CompanySales::calcTotals( int time )
{
int total = 0;
cout << setw( 4 );
for ( int counter = 0; counter < time; counter++ )
{
total += productsAndSales[counter][0];
}
return total0;
}
| Don't use the global total, make it an argument.
int totals = calcTotals(time-1, 0); // Call it starting at the end,
// so we don't have to pass along the `time`
int CompanySales::calcTotals( int counter, int total )
{
if ( counter == 0 ) {
return total;
}
else {
return calcTotals(counter - 1, total + productsAndSales[counter][ 0 ]);
}
}
Now it's tail recursive too.
|
2,456,430 | 2,456,571 | Intellisense in header files | I just right now "migrated" from C# to C++/CLR. First I was annoyed, that I had to write all class' declarations twice (into .h and .cpp). Then I figured out, that I could place the code also into the h-files - it compiles at least. Well, I deleted all cpp's of my classes and now I realized, VS won't give me any Intellisense when I work on my h-files.
I guess I should not place my code in the hfiles (the code won't be reused in other projects for sure), but I find it terrible to adjust all method declarations at two places... Plus I have to switch back and forth to see what modifier my method etc. and it is not nicely all in one place like in C# (with it's pros and cons).
I'm sorry this is a newbie question, but I just wanted to make sure that there isn't any possibility to enable intellisense for hfiles. Or at least to learn, that I am completely on the wrong path...
Thanks, David
| You're blowing intellisense out of the water because code for every class is being inlined into every implementation file, and that's just more data than Intellisense can parse reliably. It starts failing due to timeouts.
I know you said it's annoying, but you have to put the class in twice -- that's how C++ works. If you want it to behave like C#, use C#. It's a better language for the .NET platform anyway.
|
2,456,445 | 2,456,535 | C++ how can I refactor this? | I have the code below in my test code in many places:
//
// Make a function call while expecting an exception should be thrown
//
bool exceptionThrown = false;
try
{
expectNotEqual(someData, anotherData, methodName);
}
catch(std::logic_error&)
{
exceptionThrown = true;
}
if(!exceptionThrown)
throw std::logic_error(methodName+"exception not thrown");
It would be nice (more readable, concise) if I could encapsulate all that, and do something like:
exceptionShouldBeThrown(expectNotEqual(someData, anotherData, methodName));
I dont want to use macro ...does anyone know how I could achieve the one-liner above with C++?
| I know you say no macro's, but why? They exist for generating code:
#define SHOULD_THROW(x, name) \
{ \
bool didThrow = false; \
try \
{ \
x; \
} \
catch(...) { didThrow = true; } \
\
if (!didThrow) \
throw std::logic_error(name " did not throw."); \
}
SHOULD_THROW(expectNotEqual(someData, anotherData), "expectNotEqual")
If you really don't want to use macros, you need to make a functor to call:
template <typename Func>
void should_throw(Func pFunc, const std::string& pName)
{
bool didThrow = false;
try
{
pFunc();
}
catch (...)
{
didThrow = true;
}
if (!didThrow)
throw std::logic_error(pName + " did not throw.");
}
Boost Bind helps here:
should_throw(boost::bind(expectNotEqual, someData, anotherData),
"expectNotEqual");
Of course anything that makes a functor works, like lambda's, etc. But if Boost is available, just use their testing library:
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test)
{
BOOST_CHECK_THROW(expectNotEqual(someData, anotherData) , std::logic_error);
}
|
2,456,584 | 2,456,622 | Getting Segmentation Fault in C++, but why? | I am getting segmentation fault in this code but i cant figure out why. I know a segmentation fault happens when a pointer is NULL, or when it points to a random memory address.
q = p;
while(q -> link != NULL){
q = q -> link;
}
t = new data;
t -> city = cityName;
t -> latitude = lat;
t -> longitude = lon;
q -> link = t;
This is the error am actually getting in console:
line 33: 2219 Segmentation fault sh "${SHFILE}"
| In the else clause in Database::add, you do not set t->link = NULL, so it is uninitialized.
You should add a constructor for data that initializes its members, or use the value-initializing new to ensure that everything is initialized correctly:
t = new data(); // note the parentheses
|
2,456,664 | 2,456,729 | Google protobuf in Linux | I'm working with protobuf and Linux. Where is its compiler protoc? I've downloaded the package from the main site, compiled and installed it successfully but I can't find protoc to build my own format file. Where is it?
UPDATE
Here is folder where I built protobuf:
aclocal.m4 depcomp Makefile.in
autogen.sh editors missing
CHANGES.txt examples protobuf-lite.pc
config.guess generate_descriptor_proto.sh protobuf-lite.pc.in
config.h gtest protobuf.pc
config.h.in install-sh protobuf.pc.in
config.log INSTALL.txt python
config.status java README.txt
config.sub libtool src
configure ltmain.sh stamp-h1
configure.ac m4 vsprojects
CONTRIBUTORS.txt Makefile
COPYING.txt Makefile.am
There isn't a binary file I need.
| It's probably installed into /usr/local/bin
On Ubuntu at least, you can apt-get install protobuf-compiler instead.
From the INSTALL.txt:
Installation Names
By default, 'make install' will install the package's files in
'/usr/local/bin', '/usr/local/man', etc. You can specify an
installation prefix other than '/usr/local' by giving 'configure' the
option '--prefix=PATH'.
|
2,456,862 | 2,456,880 | Why can't one ctor call another ctor to initialize the object | class Foo {
public:
Foo() { Foo(1)}
Foo(int x, int y = 0):i(x) {}
private:
int i;
}
Can anybody give me some reasonas about can I do this? If not why?
| Because the language specification doesn't allow it. Just the way the language is. Very annoying if you're used to Java or other languages that allow it. However, you get used to it after a while. All languages have their quirks, this is just one of C++'s. I'm sure the writers of the specs have their reasons.
Best way around this I've found is to make a common initialization function and have both constructors call that.
Something like this:
class Foo {
public:
Foo() {initialize(1);}
Foo(int nX) { initialize(nx); }
private:
void initialize(int nx) { x=nx; }
int x;
};
|
2,456,955 | 2,456,980 | What to do if a failed destructor can't throw an exception | I noticed that you can't throw an exception in a destructor. So my question is what should I do if destructor fails.
Another question is, under what situation a destructor might fail?
Thanks so much
| Ignore the error.
A destructor might "fail" if for example the class wraps some kind of output, and the destructor flushes and closes that output. Writing data might fail. Your options then are to terminate the program, or to catch the exception, ignore the error, and return. Usually the right design is to ignore it.
In my example, the class should also have a "close_and_flush" function, which users can call prior to object destruction if they want to know whether it succeeded or not. If the user of your class doesn't care whether the operation failed, then neither do you, and you can safely suppress the exception.
Users can then write code like this:
{
OutputObject OO;
write some stuff to OO, might throw;
do more things, might throw;
try {
OO.flush_and_close();
} catch (OutputException &e) {
log what went wrong;
maybe rethrow;
}
}
Or this:
try {
OutputObject OO;
write some stuff to OO, might throw;
do more things, might throw;
OO.flush_and_close();
} catch (AnyOldException &e) {
log what went wrong;
maybe rethrow;
}
Either way, the only time the object will be destroyed without explicit flushing by the user, is if something else throws an exception and the object is destroyed during stack unwinding. So they already know that their operation has failed, and if necessary they can roll back transactions or whatever else they have to do in response to failure.
|
2,457,072 | 2,457,086 | C++ std::equal -- rationale behind not testing for the 2 ranges having equal size? | I just wrote some code to test the behavior of std::equal, and came away surprised:
int main()
{
try
{
std::list<int> lst1;
std::list<int> lst2;
if(!std::equal(lst1.begin(), lst1.end(), lst2.begin()))
throw std::logic_error("Error: 2 empty lists should always be equal");
lst2.push_back(5);
if(std::equal(lst1.begin(), lst1.end(), lst2.begin()))
throw std::logic_error("Error: comparing 2 lists where one is not empty should not be equal");
}
catch(std::exception& e)
{
std::cerr << e.what();
}
}
The output (a surprise to me):
Error: comparing 2 lists where one is not empty should not be equal
Observation: why is it the std::equal does not first check if the 2 containers have the same size() ? Was there a legitimate reason?
|
Observation: why is it the std::equal does not first check if the 2 containers have the same size() ? Was there a legitimate reason?
How? You do do not pass containers to the function, you pass in iterators. The function has no way of knowing the size of the second container. All it can do is assume bona fide that the user passed in two valid container ranges (i.e. that the second range is correctly specified as the half-open interval [lst2.begin(), lst2.begin() - lst1.begin() + lst1.end()[) and act accordingly.
|
2,457,182 | 2,457,274 | C++ -malign-double compiler flag | I need some help on compiler flags in c++. I'm using a library that is a port to linux from windows, that has to be compiled with the -malign-double flag, "for Win32 compatibility". It's my understanding that this mean I absolutely have to compile my own code with this flag as well? How about other .so shared libraries, do they have be recompiled with this flag as well? If so, is there any way around this?
I'm a linux newbie (and c++), so even though I tried to recompile all the libraries I'm using for my project, it was just too complicated to recursively find the source for all the libraries and the libraries they're dependent on, and recompile everything.
Edit:
Thanks for the answers. Some background: This library controls the initialization and access to a USB-connected camera. The problem is that without this flag, weird things start to happen. Seemingly at random, the initialization of the camera fails, with USB connection errors. I also get some kind of memory corruption of several c-strings (const char*) that are on the stack. Basically, before I call the initialization of this camera, they point to a directory path; after the initialization, they point to the string "me". Which to me is very confusing.
| You usually dont need to change alignment settings for modern compilers.
Even if compiler will store someting unaligned, program will be not broken.
The only place where it can be needed is stuctures passed between linux and windows version of programm in binary (via files or via network). But in these cases the usage of pragma pack is better style.
Update: drivers also require binary structures to be bit-by-bit equal with specification.
|
2,457,331 | 3,214,923 | Replacement for vsscanf on msvc | I've run into an issue porting a codebase from linux (gcc) to windows (msvc). It seems like the C99 function vsscanf isn't available and has no obvious replacement.
I've read about a solution using the internal function _input_l and linking statically to the crt runtime, but unfortunately I cannot link statically since it would mess with all the plugins (as dlls) being loaded by the application.
So is there any replacement or a way to write a wrapper for vsscanf?
Update 2016-02-24:
When this was first asked there was no native replacement but since then MSVC has implemented support for this and much more.
VS2013 and later implements vsscanf and friends.
C++11 includes support as well.
| A hack that should work:
int vsscanf(const char *s, const char *fmt, va_list ap)
{
void *a[20];
int i;
for (i=0; i<sizeof(a)/sizeof(a[0]); i++) a[i] = va_arg(ap, void *);
return sscanf(s, fmt, a[0], a[1], a[2], a[3], a[4], a[5], a[6], /* etc... */);
}
Replace 20 with the max number of args you think you might need. This code isn't terribly portable but it's only intended to be used on one particular broken system missing vsscanf so that shouldn't matter so much.
|
2,457,340 | 2,457,555 | How to work with a DATE type in a COM/ATL project | I've got an ATL method that takes a DATE type, which is really a double. I can't find the class/functions for this type. Does anyone know how to operate on this type? I just need to make it into something I can get into boost::gregorian::date (yyyy/mm/dd). Also, I would really like to know what this double represents. Thanks.
| With ATL use COleDateTime for VT_DATE variants.
|
2,457,389 | 2,457,484 | Looping on a closed range | How would you fix this code?
template <typename T> void closed_range(T begin, T end)
{
for (T i = begin; i <= end; ++i) {
// do something
}
}
T is constrained to be an integer type, can be the wider of such types and can be signed or unsigned
begin can be numeric_limits<T>::min()
end can be numeric_limits<T>::max() (in which case ++i will overflow in the above code)
I've several ways, but none I really like.
| Maybe,
template <typename T> void closed_range(T begin, const T end)
if (begin <= end) {
do {
// do something
} while (begin != end && (++begin, true));
}
}
Curses, my first attempt was wrong, and the fix above isn't as pretty as I'd hoped. How about:
template <typename T> bool advance(T &value) { ++value; return true; }
template <typename T> void closed_range(T first, const T last)
if (first <= last) {
do {
// do something
} while (first != last && advance(first));
}
}
There's no ambiguity with std::advance even if T isn't an integer type, since std::advance takes 2 parameters. So the template would also work with for instance a random-access iterator, if for some reason you wanted a closed range of those.
Or how about a bit of set theory? Obviously this is massive overkill if you're only writing one loop over a closed range, but if it's something that you want to do a lot, then it makes the loop code about right. Not sure about efficiency: in a really tight loop you might want make sure the call to endof is hoisted:
#include <limits>
#include <iostream>
template <typename T>
struct omega {
T val;
bool isInfinite;
operator T() { return val; }
explicit omega(const T &v) : val(v), isInfinite(false) { }
omega &operator++() {
(val == std::numeric_limits<T>::max()) ? isInfinite = true : ++val;
return *this;
}
};
template <typename T>
bool operator==(const omega<T> &lhs, const omega<T> &rhs) {
if (lhs.isInfinite) return rhs.isInfinite;
return (!rhs.isInfinite) && lhs.val == rhs.val;
}
template <typename T>
bool operator!=(const omega<T> &lhs, const omega<T> &rhs) {
return !(lhs == rhs);
}
template <typename T>
omega<T> endof(T val) {
omega<T> e(val);
return ++e;
}
template <typename T>
void closed_range(T first, T last) {
for (omega<T> i(first); i != endof(last); ++i) {
// do something
std::cout << i << "\n";
}
}
int main() {
closed_range((short)32765, std::numeric_limits<short>::max());
closed_range((unsigned short)65533, std::numeric_limits<unsigned short>::max());
closed_range(1, 0);
}
Output:
32765
32766
32767
65533
65534
65535
Be a bit careful using other operators on omega<T> objects. I've only implemented the absolute minimum for the demonstration, and omega<T> implicitly converts to T, so you'll find that you can write expressions which potentially throw away the "infiniteness" of omega objects. You could fix that by declaring (not necessarily defining) a full set of arithmetic operators; or by throwing an exception in the conversion if isInfinite is true; or just don't worry about it on grounds that you can't accidentally convert the result back to an omega, because the constructor is explicit. But for example, omega<int>(2) < endof(2) is true, but omega<int>(INT_MAX) < endof(INT_MAX) is false.
|
2,457,409 | 2,458,396 | Programmatically Installing Fonts | How could I programmatically install a font on the Mac platform (Snow Leopard)? What steps would I need to follow? I would like for the user to input a font file, then my software installs it.
| Fonts belong in ~user/Library/Fonts/ for a single user or /Library/Fonts/ to be accessible to all users. You need to get permission in order to write to /Library/Fonts/, although there is an API for that which makes it relatively easy. (I have the code somewhere and can look it up if no one else knows offhand.)
As requested, here are some API docs:
http://developer.apple.com/mac/library/documentation/Security/Reference/authorization_ref/Reference/reference.html
This is old code I have that did the update under Carbon (hence the pascal strings). It was based on sample code which is probably somewhere in the above URL. I haven't looked into doing this under Cocoa, and this is a edited version of the code (still a bit messy), so YMMV.
int main()
{
OSStatus myStatus = -1;
char path[1024];
char myToolPath[2048];
getUpdateAppPath(myToolPath);
getFilePath(path);
if (path[0] != 0)
{
char temp[2048];
FILE *f;
printf("Attempting to open \'%s\'\n", path);
f = fopen(path, "w+");
if (f != 0) // we seem to have write permission
{
fclose(f);
SInt16 res;
sprintf(temp, "\'%s\' \'%s\'", myToolPath, path);
system(temp);
StandardAlert(kAlertNoteAlert, "\pUpdate Complete", "\pSuccessfully updated.", 0, &res);
return 0;
}
AuthorizationFlags myFlags = kAuthorizationFlagDefaults;
AuthorizationRef myAuthorizationRef;
myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
myFlags, &myAuthorizationRef);
if (myStatus != errAuthorizationSuccess)
{
SInt16 res;
StandardAlert(kAlertNoteAlert, "\pAuthorization Error", "\pCould not authorize application to update.", 0, &res);
return myStatus;
}
AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights myRights = {1, &myItems};
myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights, NULL, myFlags, NULL );
if (myStatus != errAuthorizationSuccess)
break;
char *myArguments[] = { path, NULL };
FILE *myCommunicationsPipe = NULL;
char myReadBuffer[128];
myFlags = kAuthorizationFlagDefaults;
myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, myToolPath, myFlags, myArguments,
&myCommunicationsPipe);
if (myStatus == errAuthorizationSuccess)
for(;;)
{
int bytesRead = read (fileno (myCommunicationsPipe),
myReadBuffer, sizeof (myReadBuffer));
if (bytesRead < 1) break;
write (fileno (stdout), myReadBuffer, bytesRead);
}
AuthorizationFree (myAuthorizationRef, kAuthorizationFlagDefaults); // 17
}
if (myStatus)
{
printf("Status: %ld\n", myStatus);
SInt16 res;
StandardAlert(kAlertNoteAlert, "\pUpdater Error", "\pMay not have updated properly.", 0, &res);
}
else {
SInt16 res;
StandardAlert(kAlertNoteAlert, "\pUpdate Complete", "\pSuccessfully updated.", 0, &res);
}
return myStatus;
}
|
2,457,465 | 2,457,592 | Do Java or C++ lack any OO features? | I am interested in understanding object-oriented programming in a more academic and abstract way than I currently do, and want to know if there are any object-oriented concepts Java and C++ fail to implement.
I realise neither of the languages are "pure" OO, but I am interested in what (if anything) they lack, not what they have extra.
| Off the top of my head, I'd say:
multiple dispatch
generic functions
a metaobject protocol
being able to subclass native types (I don't know that this has a name, because there are relatively few OO languages I know which don't allow this)
|
2,457,658 | 2,457,690 | How to switch iostream from binary to text mode and vice versa? | I want to read both formatted text and binary data from the same iostream. How can I do that?
Why? Imagine this situation: You have different resources, and resource loaders for them, that take a std::istream as a parameter. And there are a "resource source" that provides these streams. Resources can be both text and binary and I need to handle both cases with resource loaders.
Or other situation: Image that you have an archive with resources of mixed types. How can I get a text stream from inside the binary archive stream?
| All that binary mode does is prevent special handling of newline characters. C++ has no concept of "resources" or "resource types". Simply read everything in binary mode.
|
2,457,672 | 2,457,731 | CODE1 at SPOJ - cannot solve it | I am trying to solve the problem Secret Code on SPOJ, and it's obviously a math problem.
The full problem
For those who are lazy to go and read, it's like this:
a0, a1, a2, ..., an - sequence of N numbers
B - a Complex Number (has both real and imaginary components)
X = a0 + a1*B + a2*(B^2) + a3*(B^3) + ... + an*(B^n)
So if you are given B and X, you should find a0, a1, ..an.
I don't know how or where to start, because not even N is known, just X and B.
The problem is not as easy as expressing a number in a base B, because B is a complex number.
How can it be solved?
| The key is that a0 .. an are not arbitrary numbers, they're integers (otherwise, this wouldn't be possible in general). You're given the number X , and are asked to express it in base B. Why don't you start by working a few examples for a specific value of B?
If I asked you to write 17 in base 2, would you be able to do that? Can you find a way to generalize the algorithm you use to bases other than 2?
|
2,458,001 | 2,458,307 | C++ Question on the pow function | I'm trying to get this expression to work, I'm pretty sure its not the parenthesis because I counted all of them. Perhaps there something I'm doing wrong involving the parameter pow (x,y).
double calculatePeriodicPayment()
{
periodicPaymentcalc = (loan * ((interestRate / yearlyPayment))) / (1-((pow ((1+(interestRate / yearlyPayment)))),(-(yearlyPayment * numOfYearLoan))));
return periodicPaymentcalc;
}
| Notice how much easier it is to figure out what the function is doing if you break each step up into pieces:
(I find it even easier if your variables match the source material, so I'll name my variables after the ones Wikipedia uses.)
// amortization calculator
// uses annuity formula (http://en.wikipedia.org/wiki/Amortization_calculator)
// A = (P x i) / (1 - pow(1 + i,-n))
// Where:
// A = periodic payment amount
// P = amount of principal
// i = periodic interest rate
// n = total number of payments
double calculatePeriodicPayment()
{
const double P = loan;
const double i = interestRate / yearlyPayment;
const double n = yearlyPayment * numOfYearLoan;
const double A = (P * i) / (1 - pow(1.0 + i, -n));
return A;
}
It's much easier to confirm that the logic of this function does what it should this way.
If you're curious, substituting my variable names in, your parenthises problem is as follows:
const double A = (P * i) / (1 - pow(1 + i)), -n; // <- this is how you have it
const double A = (P * i) / (1 - pow(1 + i, -n)); // <- this is how it should be
With this grouping, you're only passing one argument to pow, which is why the compiler says no overloaded function takes 1 arguments.
Edit: You mentioned I used more variables. However, your compiler will use temporary variables much like I did. Your complex statement will be broken up into pieces, and may look something like this:
double calculatePeriodicPayment()
{
const double temp1 = interestRate / yearlyPayment;
const double temp2 = loan * temp1;
const double temp3 = interestRate / yearlyPayment;
const double temp4 = 1.0 + temp3;
const double temp5 = yearlyPayment * numOfYearLoan;
const double temp6 = -temp5;
const double temp7 = pow(temp4, temp5);
const double temp8 = 1 - temp7;
const double temp9 = temp2 / temp8;
periodicPaymentcalc = temp9;
return periodicPaymentcalc;
}
Mine will also be broken up, and will look like:
double calculatePeriodicPayment()
{
const double P = loan;
const double i = interestRate / yearlyPayment;
const double n = yearlyPayment * numOfYearLoan;
const double temp1 = P * i;
const double temp2 = 1.0 + i;
const double temp3 = -n;
const double temp4 = pow(temp2, temp3);
const double temp5 = 1 - temp4;
const double temp6 = temp1 / temp5;
const double A = temp6;
return A;
}
Perhaps there are some optimizations that the compiler will use, such as noticing that it uses interestRate / yearlyPayment twice in your function, and use the same temporary for both places, but there's no gurantee this will happen. Notice that we use pretty much the same number of variables in both of our functions. I just used more named variables, and fewer unnamed temporaries.
|
2,458,025 | 5,615,856 | How to properly downcast in C# with a SWIG generated interface? | I've got a very large and mature C++ code base that I'm trying to use SWIG on to generate a C# interface for. I cannot change the actual C++ code itself but we can use whatever SWIG offers in the way of extending/updating it. I'm facing an issue where a C++ function that is written as below is causing issues in C#.
A* SomeClass::next(A*)
The caller might do something like:
A* acurr = 0;
while( (acurr = sc->next(acurr)) != 0 ){
if( acurr isoftype B ){
B* b = (B*)a;
...do some stuff with b..
}
elseif( acurr isoftype C )
...
}
Essentially, iterating through a container of elements that, depending on their true type, does something different. The SWIG generated C# layer for the "next" function unfortunately does the following:
return new A();
So the calling code in C# cannot determine if the returned object is actually a derived class or not, it actually appears to always be the base class (which does make sense). I've come across several solutions:
Use the %extend SWIG keyword to add a method on an object and ultimately call dynamic_cast. The downside to this approach, as I see it, is that this requires you to know the inheritance hierarchy. In my case it is rather huge and I see this is as a maintenance issue.
Use the %factory keyword to supply the method and the derived types and have SWIG automatically generate the dynamic_cast code. This appears to be a better solution that the first, however upon a deeper look it still requires you to hunt down all the methods and all the possible derived types it could return. Again, a huge maintenance issue. I wish I had a doc link for this but I can't find one. I found out about this functionality by looking through the example code that comes with SWIG.
Create a C# method to create an instance of the derived object and transfer the cPtr to the new instance. While I consider this clumsy, it does work. See an example below.
public static object castTo(object fromObj, Type toType)
{
object retval = null;
BaseClass fromObj2 = fromObj as BaseClass;
HandleRef hr = BaseClass.getCPtr(fromObj2);
IntPtr cPtr = hr.Handle;
object toObj = Activator.CreateInstance(toType, cPtr, false);
// make sure it actually is what we think it is
if (fromObj.GetType().IsInstanceOfType(toObj))
{
return toObj;
}
return retval;
}
Are these really the options? And if I'm not willing to dig through all the existing functions and class derivations, then I'm left with #3? Any help would be appreciated.
| By default SWIG generates C# and Java code that does not support downcast for polymorphic return types. I found a straightforward way to solve this, provided your C++ code has a way to identify the concrete class of the C++ instances that are returned. That is, my technique will work only if the C++ API you are wrapping with SWIG has something similar to C# object.GetType() or Java Object.getClass().
The solution is to add a C# intermediate class method to instantiate the concrete class that the C++ says it is. Then, use %typemap(out) to tell SWIG to use this intermediate class method when returning the abstract classes.
That's an awfully terse explanation, so refer to my blog article that shows how to generate polymorphic C# and Java that you can downcast. It has all the details.
|
2,458,028 | 2,486,043 | Is There a Good Pattern for Creating a Unique Id based on a Type? | I have a template that creates a unique identifier for each type it is instanced. Here's a streamlined version of the template:
template <typename T>
class arType {
static const arType Id; // this will be unique for every instantiation of arType<>.
}
// Address of Id is used for identification.
#define PA_TYPE_TAG(T) (&arType<T >::Id)
This works when you have an executable made purely of static libraries. Unfortunately we're moving to an executable made up of dlls. Each dlls could potentially have its own copy of Id for a type.
One obvious solution is to explicitly instantiate all instances of arType. Unfortunately this is cumbersome, and I'd like to ask if anyone can propose a better solution?
| Return a std::type_info object from a function on each object and use operator == on the result. You can sort them by using the before() function which returns the collation order.
It's specifically designed to do what you want. You could wrap it in an opaque "id" type with an operator< if you wanted to hide how it works underneath.
http://www.cplusplus.com/reference/std/typeinfo/type_info/
|
2,458,087 | 2,458,740 | How do you do masked password entry on windows using character overwriting? | Currently I am using this implementation to hide user input during password entry:
void setEcho(bool enable) {
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
if(enable) {
mode |= ENABLE_ECHO_INPUT;
} else {
mode &= ~ENABLE_ECHO_INPUT;
}
SetConsoleMode(hStdin, mode);
}
The user needs to be able to have positive feed back that text entry is being made. What techniques are available in a Win32 environment using C++?
| The solution is to not use stdio.h but to use conio.h. The following routine solves the above problem. Note that disabling echo is no longer needed:
void scanPass(char* passwordEntry, int length) {
int index, ch;
for(index = 0; index < (length - 1) && ((ch = _getch()) != EOF)
&& (ch != 13); index++) {
passwordEntry[index] = (char)ch;
_putch('*');
}
passwordEntry[index] = '\0';
}
The answer in this case is to use the correct tool for the job. (And to know of the right tool.)
|
2,458,090 | 2,458,179 | Can we overload a function based on only whether a parameter is a value or a reference? | I got the answer NO! Because passing by value and passing by reference looks identical to the caller.
However, the code below compiles right
class A {
public:
void f(int i) {}
void f(int& i) {}
};
But when I try to use it, there is compile error.
int main () {
A a;
int i = 9;
int& j = i;
a.f(1);
a.f(i);
a.f(j);
return 0;
}
Why does not the compiler disable it even without knowing it is going to be used?
| Yes, they can be overloaded based on reference or not. That is why it's perfectly fine to have them coexist like that; they are different.
The problem has to do with ambiguity. While f(1) can only be called on one variation, f(i) can be called on both. Neither is preferable, therefore you get an error for ambiguity. If you added a third function, foo (const int&), all calls would be ambiguous. But all are still overloads of each other, and non-conflicting.
I agree it's strange to be able to have three overloads of a function, and be able to directly call none. Perhaps someone else has more to add.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.