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
|
|---|---|---|---|---|
706,921
| 2,723,270
|
Problems with setting application icon
|
(I'm using Visual Studio 2008, though I remember having similar problems with older versions as well.)
I've tried several different methods (many of them mentioned in this other question), but I am still having some strange issues:
When including an icon as a resource, it does show up as the executable file's icon immediately, but for the icon to show up on the taskbar, I have to restart the computer. Until then, it continues to show up as whatever the previous icon was. Cleaning the solution, restarting VS, doesn't have any effect. Not a really big issue, as it won't affect a released exe, but it would be nice to know where it's keeping the old icon cached and how to get rid of it.
No matter what I do, the icon displayed when alt-tabbing is the default app icon (square and white and generic). This includes embedding the icon in the executable, as well as setting ICON_BIG with WM_SETICON.
As for the second matter, my code looks something like:
hIcon = (HICON)(
LoadImage( NULL, szFilename, IMAGE_ICON, 32, 32, LR_LOADFROMFILE ) );
if( hIcon )
SendMessage( hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon );
However, after sending WM_SETICON, GetLastError() returns 6, "The handle is invalid.". hWnd is a valid window handle, and hIcon appears to be a valid icon handle. I've tried searching for reasons why WM_SETICON could cause that error, and at the very least, to figure out WHICH handle it thinks is invalid, but no luck yet. I've cleared the error code immediately before calling SendMessage(), so it has to be set somewhere in the processing of the message.
I tried an alternate method, loading the icon from the exe itself, where the ID of the resource is 101 (it's the first and only resource included):
hIcon = (HICON)(
LoadImage( GetModuleHandle( NULL ), MAKEINTRESOURCE( 101 ),
IMAGE_ICON, 48, 48, 0 ) );
if( hIcon )
SendMessage( hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon );
... but the same thing happens; after calling SendMessage(), GetLastError() gives the same error status.
I've tried different dimensions (such as 48x48, all of which are present in the icon file), but to no different effect. I know it's definitely finding and loading the images, because if I specify a size that doesn't exist or an invalid resource ID or the wrong filename (depending on how I am loading it), it fails out long before SendMessage().
Strangely, if I specify ICON_SMALL instead of ICON_BIG, the call succeeds with no error status, but from the docs, I need to use ICON_BIG to set the icon used while alt-tabbing. Also, if I use ICON_BIG but load the 16x16 icon, I get no error status, but nothing changes.
Any ideas about what could be causing WM_SETICON to fail? Anything terribly wrong with any of the code I've posted (aside from formatting/style/casting issues, as it's simplified to just the basics)?
|
I've revisited this to see if I can close out my question. I have been unable to get the app's icon to show up in the alt-tab list just through embedding it in the executable; it will show up in the taskbar, as the file's icon in Explorer, and elsewhere just fine.
I figured I'd try something simpler for setting the icon manually, and went with LoadIcon() instead, as the code below shows:
HICON hIcon = LoadIcon( GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1) );
if( hIcon )
{
SendMessage( GetHandle(), WM_SETICON, ICON_BIG, (LPARAM)hIcon );
DestroyIcon( hIcon );
}
// ... Same for ICON_SMALL
This seems to have done the trick. I really don't know why, but so far it's the only change that had any effect. It's really not an issue I should spend any more time on, so I'll just go with this.
|
707,081
| 707,180
|
Are operator overloadings in C++ more trouble than they're worth?
|
In my experience teaching C++, operator overloading is one of those topics that causes the most grief to students. Even looking at questions here at stackoverflow: for example, make the + operator external or a member? How to handle symmetry, etc., it seems like it's a lot of trouble.
When I moved from C++ to Java, I was worried I would miss that ability, but with the exception of operators like [] or (), I haven't really ever felt the need to overload operators. In fact, I feel programs without them are more readable.
Note: I put this as a community wiki. Let's discuss this. I want to hear opinions.
|
Overloaded operators are like spice. A little can make something better; too much can make it unpalatable.
|
707,332
| 707,338
|
Printing a custom number of header delimiters based on message length
|
Say I want to print:
============
Some message
============
And:
=======================
Other Message long one
=======================
The number of "=" changes based on the message length. What is the most efficient way to print this sort of a thing?
No boost, just STL please.
|
std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
|
707,370
| 707,426
|
Clean, efficient algorithm for wrapping integers in C++
|
/**
* Returns a number between kLowerBound and kUpperBound
* e.g.: Wrap(-1, 0, 4); // Returns 4
* e.g.: Wrap(5, 0, 4); // Returns 0
*/
int Wrap(int const kX, int const kLowerBound, int const kUpperBound)
{
// Suggest an implementation?
}
|
The sign of a % b is only defined if a and b are both non-negative.
int Wrap(int kX, int const kLowerBound, int const kUpperBound)
{
int range_size = kUpperBound - kLowerBound + 1;
if (kX < kLowerBound)
kX += range_size * ((kLowerBound - kX) / range_size + 1);
return kLowerBound + (kX - kLowerBound) % range_size;
}
|
707,447
| 707,479
|
Single XMLHTTPRequest object to make multiple requests
|
Does anyone know if there is a way to use a single XMLHTTPRequest object to send multiple asynchronous requests. I can do it with a single request and get a response back from my onreadystatechange() handler.
I'm wondering if there's a way to use the same object to send multiple parallel requests but I'm not seeing any way to match a response to a request from the onreadystatechange() function.
|
Short answer: You can't.
Question you really need to ask yourself is why would you want that over multiple XMLHTTPRequest objects ? There's hardly a downside to instantiating a dozen or so objects.
|
707,492
| 707,862
|
How do I paint with QPainter?
|
I have started learning Qt recently.
I did not get quite clear how can I paint using QPainter class. Let`s say I want just to place a few points in the window:
class PointDrawer: public QWidget {
Q_OBJECT
private:
QPainter p;
public:
PointDrawer(QWidget* obj=0): QWidget(obj), p(this) {}
virtual void paintEvent(QPaintEvent*) {
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
}
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
PointDrawer drawer;
drawer.resize(200, 200);
drawer.show();
return app.exec();
}
And after that, I got nothing!Can you please tell me where I am wrong?
|
I think the problem is your QPainter initialization.
You could just create the QPainter like in hydroes' answer, it would look like this then:
class PointDrawer: public QWidget {
Q_OBJECT
public:
PointDrawer(QWidget* obj=0): QWidget(obj) {}
virtual void paintEvent(QPaintEvent*) {
QPainter p(this);
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
}
}
It could also use something like this, but I don't really recommend it (I just prefer the other solution):
class PointDrawer: public QWidget {
Q_OBJECT
private:
QPainter p;
public:
PointDrawer(QWidget* obj=0): QWidget(obj) {}
virtual void paintEvent(QPaintEvent*) {
p.begin(this);
p.setPen(QPen(Qt::black, 3));
int n = 8;
while(...) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal y = 50 + sin(fAngle) * 40;
p.drawPoint(QPointF(x, y));
i++;
}
p.end();
}
}
The QPainter::begin(this) and QPainter::end() calls are essential in the second example. In the first example, you can think of QPainter::begin(this) being called in the constructor and QPainter::end() in the destructor
For the reason, I'm guessing:
As QPaintDevices are usually double buffered in QT4, QPainter::end() might be where the image is transferred to the graphic memory.
|
707,497
| 707,876
|
Set app to require elevation?
|
I'm working on the bootstrap application of a new installer for some of our products. So far, I've been relying on two things that I read about somewhere:
Applications whose name contains "setup" or "install" will run elevated by default.
Applications that run elevated will launch other applications in elevated mode.
Recent testing has found that one or both of these statements is false, because one of the applications that I'm launching is a third party installer that requires elevation, and it's failing because of the elevation requirement.
How do I set my application to require elevation? I know it has something to do with the manifest file. As I'm working in Visual Studio 2008, and the manifest file is generated, I'd like to know what to enter into the project's properties and where to make it require elevation.
|
When I couldn't find application manifest as a new item that could be added to my project, I went into the online help and found this:
configure the VS2008 in Configuration Properties - Linker - Manifest File - UAC Execution Level (requireAdministrator)
That did the trick.
|
708,089
| 708,101
|
C++ using namespaces to avoid long paths
|
I am still learning C++, and I have never really created my own namespaces before. I was experimenting with them and while I got most things to work, there's one thing that I still can't seem to do. I would like to be able to call a static method within a class without typing something like NameOfClass::method. Here is what I thought the code should look like, but it fails to compile:
File A.h,
namespace Test
{
class A
{
public:
static int foo() { return 42; }
};
}
File main.cpp,
#include <iostream>
#include "A.h"
using namespace std;
using namespace Test::A;
int main()
{
cout << foo() << endl;
return 0;
}
The compiler gives me:
main.cpp:6: error: ‘A’ is not a namespace-name
main.cpp:6: error: expected namespace-name before ‘;’ token
main.cpp: In function ‘int main()’:
main.cpp:10: error: ‘foo’ was not declared in this scope
Is it possible to do what I am trying to do without typing A::foo?
|
There is no way around it you need to specify the class name for static methods.
using namespace Test;
Then:
int answerToEverything = A::foo();
|
708,114
| 708,261
|
Convert Byte Array into Bitset
|
I have a byte array generated by a random number generator. I want to put this into the STL bitset.
Unfortunately, it looks like Bitset only supports the following constructors:
A string of 1's and 0's like "10101011"
An unsigned long. (my byte array will be longer)
The only solution I can think of now is to read the byte array bit by bit and make a string of 1's and 0's. Does anyone have a more efficient solution?
|
Something like this?
#include <bitset>
#include <climits>
template<size_t numBytes>
std::bitset<numBytes * CHAR_BIT> bytesToBitset(uint8_t *data)
{
std::bitset<numBytes * CHAR_BIT> b;
for(int i = 0; i < numBytes; ++i)
{
uint8_t cur = data[i];
int offset = i * CHAR_BIT;
for(int bit = 0; bit < CHAR_BIT; ++bit)
{
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
return b;
}
And an example usage:
int main()
{
std::array<uint8_t, 4> bytes = { 0xDE, 0xAD, 0xBE, 0xEF };
auto bits = bytesToBitset<bytes.size()>(bytes.data());
std::cout << bits << std::endl;
}
|
708,285
| 708,322
|
Is there some sort of tool or helper to port an MFC/C++ app to OS X/Cocoa?
|
I have a significant codebase written in MFC and am tasked with creating a port for Mac OS X. I know that I'm going to have to roll up my sleeves at some point and do alot of grunt work to get everything working correctly, but are there any tools out there that might get me partway?
|
I'm working on one.
From the GUI point of view, the new version of AppMaker is based around an import/generate model. Most of commercial work I've done with AppMaker has been the other way, porting Macintosh applications to Windows. However, there's no reason why the same principles can't be applied in reverse.
AppMaker v2 had a very good importer for PowerPlant UI resources and traditional Mac dialogs. As it is only able to run on Classic, that code base has been discarded (you really don't want to know) and the final generator languge I wrote for AppMaker v2 is an XML exporter which dumps the entire object model to an extended XAML.
I already have a XAML UI generator and am currently working on a Cocoa xib generator - one of the reasons for going to WWDC in June. The focus at this time is on import/generator suites before returning my attention to a GUI editor.
I wrote PP2MFC to allow PowerPlant applications to be compiled for Windows - a cross-platform solution needed because no other framework or cross-platform tool at the time (1997) would perform well enough for the hardware requirements. I've since discussed an opposite program with someone I could chase up and I'm sure an MFC portability layer could be created to map to Cocoa objects. Whilst many developers have a poor opinion of MFC's message-map architecture, the heavily macro-based API sits on top of a reasonably clean OO framework.
This is the kind of project where you need to think about long-term maintainability - do you want something which ends up as large chunks of MFC code working with Cocoa or do you want to migrate to an idiomatic Cocoa program.
Any further discussion should probably be taken off SO - contact me at dent at oofile.com.au but I'm happy to debate technicalities and feasibility on here. The combination of code generation and skinny framework adaptor layers works better than most people expect.
|
708,460
| 708,493
|
Compiler error with `<<`
|
I've been working on getting this program complete where it saves multiple structs to a file, can read them back and edit them, then save them all back to a file. I've been working on the logic of this not to mention lots of help from others and a ton of googling hours... now I am getting a compile error. Any help would be very appreciated.
Code:
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
struct InventoryItem {
string Item;
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
int dateAdded;
} ;
int main(void)
{
vector<InventoryItem> structList;
ofstream out("data.dat");
writeVector( out, structList );
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i; // error C2679
}
}
Compiler error:
1>.\Project 5.cpp(128) : error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const InventoryItem' (or there is no acceptable conversion)
// listed overload variants skipped
1> while trying to match the argument list '(std::ofstream, const InventoryItem)'
1> .\Project 5.cpp(46) : see reference to function template instantiation 'void writeVector<InventoryItem>(std::ofstream &,const std::vector<_Ty> &)' being compiled
1> with
1> [
1> _Ty=InventoryItem
1> ]
|
You have no operator<< defined that would specify how your InventoryItem should be printed to an output stream. You try to print it and the compiler doesn't know how. You need to define a function like this one:
std::ostream& operator<<(std::ostream &strm, const InventoryItem &i) {
return strm << i.Item << " (" << i.Description << ")";
}
|
708,742
| 708,945
|
C++ std::transform side effect
|
I've implementation of UnaryOperation like this
struct Converter
{
Converter( std::size_t value ):
value_( value ), i_( 0 )
{}
std::string operator() ( const std::string& word )
{
return ( value_ & ( 1 << i_++ ) ) ?
word:
std::string( word.size(), ' ' );
}
std::size_t value_;
std::size_t i_;
};
And I use it like
std::vector v;
// initialization of v
std::transform( v.begin(), v.end(),
std::back_inserter( result ),
Converter( data ) );
My question is can I rely on my assumption that algorithm will call my 'Converter operator ()' in the order that 'Converter::i_' will correspond to number of element in 'v'.
Please quote the standard in case I can't rely on the order or put the stl-like solution that avoid possible problem if any.
Thanks.
Edit:
I am aware of "no Side effect" requirements in the standard for the transform algorithm. I can't find what is exactly "side effect" for functors in the same standard.
Maybe there is some good-looking-boost-like solution for this task?
|
Qute from standard:
25.2.3 Transform [lib.alg.transform]
Requires:
op and binary_op shall not have any side effects.
Side Effect ( wikipedia definition )
In your case we have next side effect:
Converter c( data );
c( some_const_value ) != c( some_const_value );
You don't have any guarantees for your algorithms, but I belive that it will works on almost all stl implementations.
Suggested solution
It seems I know one way to do what you need:
use boost::counting_iterator - for iterate over two containers;
it will looks like:
bool bit_enabled( size_t data, unsigned char number )
{
return ( data & 1 << number ) != 0;
}
std::string select_word(
const std::string& word,
size_t data,
size_t number )
{
return bit_enabled( data, number ) ? word : std::string( ' ', word.length() );
}
const size_t data = 7;
const boost::array< std::string, 3 > vocabulary = { "a", "b", "c" };
std::vector< std::string > result;
std::transform(
vocabulary.begin(),
vocabulary.end(),
boost::counting_iterator< size_t >(0),
back_inserter( result ),
boost::bind( &select_word, _1, data, _2 )
);
Also maybe if you will define bit iterator or will use some bit container you will can use boost::zip_iterator for iterate both containers.
EDIT:
Yestarday I found interest article which contain definition of Side Effect by standard.
The Standard defines a side effect as
follows: Accessing an object
designated by a volatile lvalue,
modifying an object, calling a library
I/O function, or calling a function
that does any of those operations are
all side effects, which are changes in
the state of the execution
environment.
EDIT:
I hope it will be latest edit.
I am always tought that "no have side effect" mean:
f(a) should be equal f(a) always. ( f independed from execution environment: memory/cpu/global variables/member variables as in your case etc).
"Not produce side effect" mean - don't changing execution environment.
But in c++ standard we have more low-level defintion for Side effect.
Thing what you do in your example named as Stateful functor.
Standard doesn't say about "Statefull" functors, but also doesn't say about count of copies of your functor - you couldn't use this trick because it is unspecified behavior.
See Standard Library Issues list ( similar issue for predicat ):
http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/lwg-active.html#92
|
708,807
| 709,028
|
GCC/Make Build Time Optimizations
|
We have project which uses gcc and make files. Project also contains of one big subproject (SDK) and a lot of relatively small subprojects which use that SDK and some shared framework.
We use precompiled headers, but that helps only for re-compilation to be faster.
Is there any known techniques and tools to help with build-time optimizations? Or maybe you know some articles/resources about this or related topics?
|
You can tackle the problem from two sides: refactor the code to reduce the complexity the compiler is seeing, or speed up the compiler execution.
Without touching the code, you can add more compilation power into it. Use ccache to avoid recompiling files you have already compiled and distcc to distribute the build time among more machines. Use make -j where N is the number of cores+1 if you compile locally, or a bigger number for distributed builds. That flag will run more than one compiler in parallel.
Refactoring the code. Prefer forward declaration to includes (simple). Decouple as much as you can to avoid dependencies (use the PIMPL idiom).
Template instantiation is expensive, they are recompiled in every compilation unit that uses them. If you can refactor your templates as to forward declare them and then instantiate them in only one compilation unit.
|
708,872
| 708,874
|
C++ runtime required?
|
Why do some C++ projects require a runtime package to be installed, while others do not?
EDIT:How to make a project to work without the runtime?
|
Some will have been statically linked, while others will depend on a dynamic library, loaded at run-time. To link your own project statically, you need to change your project configuration - how you do this depends on the compiler/linker and/or IDE you are using.
|
708,948
| 708,957
|
When will STL iterator be equal to zero?
|
I have a program which is like this
list<int>:: iterator n = alist.begin();
while(n!= (list<int>::iterator)0)
{
printf("Element is %d\n",*n);
n = alist.erase(n);
}
So here i am comparing iterator with zero.
but after deleting the last element the compiler is showing this error.
*** glibc detected *** ./new: free(): invalid pointer: 0xbf99cb10 ***
======= Backtrace: =========
/lib/libc.so.6[0xb7d956e1]
/lib/libc.so.6(cfree+0x89)[0xb7d96d79]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f3ff81]
./new[0x8048c81]
./new[0x8048ca6]
./new[0x8048d07]
./new[0x8048d39]
./new(__gxx_personality_v0+0x216)[0x804888e]
/lib/libc.so.6(__libc_start_main+0xdc)[0xb7d46f9c]
./new(__gxx_personality_v0+0x49)[0x80486c1]
======= Memory map: ========
08048000-0804a000 r-xp 00000000 08:09 3704751 /home/sathya/chaithra/archivesthrash/new
If I want the iterator to be zero if the queue/list is empty.. what i should do?
Because in my project I need to compare this iterator with zero only and not with alist.end()..
What may be the probable solution to this...?
|
Why do you think the iterator will ever "be zero"? Iterators are not pointers or indexes. If you need to check if a container is empty, use the empty() member function.
|
709,146
| 709,161
|
How do I clear the std::queue efficiently?
|
I am using std::queue for implementing JobQueue class. ( Basically this class process each job in FIFO manner).
In one scenario, I want to clear the queue in one shot( delete all jobs from the queue).
I don't see any clear method available in std::queue class.
How do I efficiently implement the clear method for JobQueue class ?
I have one simple solution of popping in a loop but I am looking for better ways.
//Clears the job queue
void JobQueue ::clearJobs()
{
// I want to avoid pop in a loop
while (!m_Queue.empty())
{
m_Queue.pop();
}
}
|
A common idiom for clearing standard containers is swapping with an empty version of the container:
void clear( std::queue<int> &q )
{
std::queue<int> empty;
std::swap( q, empty );
}
It is also the only way of actually clearing the memory held inside some containers (std::vector)
|
709,790
| 709,996
|
How can I know the address of owner object in C++?
|
I would like to create in C++ a Notifier class that I will use in other objects to notify various holders when the object gets destroyed.
template <class Owner>
class Notifier<Owner> {
public:
Notifier(Owner* owner);
~Notifier(); // Notifies the owner that an object is destroyed
};
class Owner;
class Owned {
public:
Owned(Owner* owner);
private:
Notifier<Owner> _notifier;
};
My point is that as I have a dense and complicated object graph, I'd like to avoid storing the address of the owned object in the notifier. Is there a way to change my notifier class so that it can deduce the owned object's address from its own address and an offset that would be computed at compile time?
Note also that any object may have to notify several 'owners', possibly from the same class.
Thanks.
|
Or something like this :
Inherit from your notifier and add Owned as template parameter. Then you can have a owned method available inside the notifier :
template < class Owner , class Owned >
class Notifier
{
public:
Notifier(Owner* owner)
{}
Owned * owned()
{ return static_cast< Owned * >( this ); }
~Notifier()
{
// notify owner with owned()
}
};
class Owner
{};
class Owned : public Notifier< Owner , Owned >
{
public:
Owned( Owner * owner ) : Notifier< Owner , Owned >( owner )
{}
};
|
709,795
| 710,300
|
debug stack overflow in windows?
|
So I'm trying to debug this strange problem where a process ends without calling some destructors...
In the VS (2005) debugger, I hit 'Break all' and look around in the call stacks of the threads of the misteriously disappearing process, when I see this:
smells like SO http://img6.imageshack.us/img6/7628/95434880.jpg
This definitely looks like a SO in the making, which would explain why the process runs to its happy place without packing its suitcase first.
The problem is, the VS debugger's call stack only shows what you can see in the image.
So my question is: how can I find where the infinite recursion call starts?
I read somewhere that in Linux you can attach a callback to the SIGSEGV handler and get more info on what's going on.
Is there anything similar on Windows?
|
To control what Windows does in case of an access violation (SIGSEGV-equivalent), call SetErrorMode (pass it parameter 0 to force a popup in case of errors, allowing you to attach to it with a debugger.)
However, based on the stack trace you have already obtained, attaching with a debugger on fault may yield no additional information. Either your stack has been corrupted, or the depth of recursion has exceeded the maximum number of frames displayable by VS. In the latter case, you may want to decrease the default stack size of the process (use the /F switch or equivalent option in the Project properties) in order to make the problem manifest itself sooner, and make sure that VS will display all frames. You may, alternatively, want to stick a breakpoint in std::basic_filebuf<>::flush() and walk through it until the destruction phase (or disable it until just prior to the destruction phase.)
|
709,914
| 709,950
|
Windows: Overwrite File In Use
|
I am trying to write a utility that will allow moving files in Windows, and when it finds a file in use, will set that file to be moved on reboot.
It seems that MoveFileEx (http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) is the right call for this, however I cannot figure out what error code I'm looking for from GetLastError (http://msdn.microsoft.com/en-us/library/ms679360(VS.85).aspx) to see that the file was in use.
I want the utility to fail when there is an actual permissions problem. Is there anyway to differentiate a you-can't-write-there and a in-use overwrite error?
Also, if I have the files I am moving in the user's temporary folder, will they get deleted before the delayed rename?
|
You have to call CreateFile first to see if the file is in use.
To see if the file is in use:
If you get a valid file handle then you know the file does not have conflicting sharing permissions with a process that already has this file open.
If you specify no sharing access (0 to the dwShareMode parameter of the CreateFile call), then you will not get a file handle if any other process is currently using that file in any way. GetLastError in this case would return: ERROR_SHARING_VIOLATION (32)
To see if there is a security problem with accessing the file:
To see if there is a permissions problem accessing that file, the CreateFile call will also fail but with a different GetLastError. You will get: ERROR_ACCESS_DENIED (5)
|
710,253
| 711,462
|
How to load all files from a directory?
|
Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.
Edit:
For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.
|
For Lua, you want the module Lua Filesystem.
As observed by Nick, accessing the file system itself (as opposed to individual files) is outside the scope of the C and C++ standards. Since Lua itself is (with the exception of the dynamic loader used to implement require() for C modules) written in standard C, the core language lacks many file system features.
However, it is easy to extend the Lua core since (nearly) any platform that has a file system also supports DLLs or shared libraries. Lua File system is a portable library that adds support for directory iteration, file attribute discovery, and the like.
With lfs, emulating some of the capability of DIR in Lua is essentially as simple as:
require "lfs"
dot = arg[1] or "."
for name in lfs.dir(dot) do
local fqn = dot.."/"..name
local attr = lfs.attributes(fqn)
print(name, attr.mode, os.date("%Y-%m-%d %H:%M",attr.modification), attr.size)
end
Which produces output that looks like:
E:...>t-lfs.lua
. directory 2009-04-02 13:23 0
.. directory 2009-04-02 13:18 0
foo.txt file 2009-02-23 01:56 0
t-lfs.lua file 2009-04-02 13:18 241
E:...>
If your copy of Lua came from Lua for Windows, then you already have lfs installed, and the above sample will work out of the box.
Edit: Incidentally, the Lua solution might also be a sensible C or C++ solution. The Lua core is not at all large, provides a dynamic, garbage-collected language, and is easy to interact with from C either as a hosting application or as an extension module. To use lfs from a C application, you would link with the Lua DLL, initialize a Lua state, and get the state to execute the require"lfs" either via luaL_dostring() or by using the C API to retrieve the require() function from the global table, push the string "lfs", and call the Lua function with something like lua_pcall(L,1,1,0), which leaves the lfs table on the top of the Lua stack.
This approach probably makes the most sense if you already had a need for an embedded scripting language, and Lua meets your requirements.
|
710,432
| 710,447
|
"No appropriate default constructor available" error in Visual C++
|
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.
The class I'm creating, called TwoDayPackage is derived from a class called Package.
This is how I defined the constructor:
TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);
This is how I implement the constructor:
TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}
This is how i use it in my main function.
TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);
I know my argument list is pretty long, there's a reason for that.
Thanks.
|
Should use:
TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
:Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost)
{
flatRate = flat;
}
|
710,604
| 36,564,745
|
How do I set EOF on an istream without reading formatted input?
|
I'm doing a read in on a file character by character using istream::get(). How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace) and set the corresponding flags (EOF, bad, etc)?
|
You can strip any amount of leading (or trailing, as it were) whitespace from a stream at any time by reading to std::ws. For instance, if we were reading a file from STDIN, we would do:
std::cin >> std::ws
Credit to this comment on another version of this question, asked four years later.
|
710,607
| 710,627
|
Why do I get a segmentation fault when calling a virtual method in this code?
|
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.
(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:
#include <iostream>
using namespace std;
class Base
{
protected:
char *name;
public:
Base(char *name)
{
cout << name << ": Base class cons" << endl;
}
~Base()
{
cout << name << ": Base class des" << endl;
}
virtual void disp();
};
void Base::disp()
{
cout << name << ": Base disp()" << endl;
}
class Child : public Base
{
public:
Child(char *name):
Base(name)
{
cout << name << ": Child class cons" << endl;
}
~Child()
{
cout << name << ": Child class des" << endl;
}
virtual void disp()
{
cout << name << ": Child disp()" << endl;
}
};
int main()
{
//Base b;
//b.disp();
Base c = Child("2");
c.disp();
}
Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!
|
name - is unintialized in Base
also you have another problem:
Base c = Child("2");
I don't think it's what you want. Your code will create an instance of Base from casted Child. But I think you want work with Child instance based on Base interface; you should instead write:
Base *c = new Child("2");
also, to avoid future bugs, declare destructor in base as virtual.
|
710,638
| 983,968
|
Simple email program / library recommendations
|
I am needing to implement email notifications for a C++ project. Basically a user provides all the relevant information for their email account and on certain events this component would fire off an email. Ideally I would like to find a small cross platform open source command line project that I can exec from within my project and parse the output. Something like blat but it would also support SSL connections and can be used in both Windows(XP and 2003) and Linux (Ubuntu 6.06 and 8.04)
I could also use a library if it were simple enough and licensed under a commercial friendly license, but would be open to hearing all suggestions.
Thank you very much in advance for any recommendations
|
I ended up using the Perl script sendEmail. A windows binary was available and building a new binary after modifying the Perl script was not too hard to do at all. The script also had no issues running in the LTE Ubuntu environments after the required Debian packages were installed.
|
710,807
| 710,832
|
rules with temporary objects and args by reference
|
say I have a class:
class A
{
public:
A() {}
};
and a function:
void x(const A & s) {}
and I do:
x(A());
could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?
Thanks!
|
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
|
711,350
| 711,386
|
Learning to work with audio in C++
|
My degree was in audio engineering, but I'm fairly new to programming. I'd like to learn how to work with audio in a programming environment, partly so I can learn C++ better through interesting projects.
First off, is C++ the right language for this? Is there any reason I shouldn't be using it? I've heard of Soundfile and some other libraries - what would you recommend?
Finally, does anyone know of any good tutorials in this subject? I've learnt the basics of DSP - I just want to program it!
EDIT: I use Windows. I'd like to play about with real-time stuff, a bit like Max/MSP but with more control.
|
It really depends on what kind of audio work you want to do, If you want to implement audio for a game, C++ is sure the right language. There are many libraries around, OpenAL is great, free and multiplatform. I also used DirectSound and Fmod with great sucess. Check them out, it all depends on your needs.
|
711,603
| 711,701
|
Docking control bars/panes to CMDIFrameWndEx?
|
In one of our applications I've used some of the MFC classes to allow docking a sidebar window, approximately like so:
CDialogBar* bar = new CDialogBar;
bar->Create(this, IDD, WS_CHILD | WS_VISIBLE | CBRS_RIGHT | CBRS_TOOLTIPS, IDD));
bar->EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_RIGHT | CBRS_ALIGN_LEFT);
DockControlBar(bar, AFX_IDW_DOCKBAR_RIGHT);
This all works fine.
I want to do a similar thing now in another application. Unfortunately it has been changed to use some classes from the MFC "feature pack", which are very pretty but this approach no longer works (it asserts, which I can fix with some minor modification but then the sidebar doesn't appear). The documentation for these new classes is woeful, so I'm having quite a bit of trouble figuring out what I'm supposed to do. I've tried what seems to be the "new" approach:
CPaneDialog* pane = new CPaneDialog;
pane->Create("pane", this, TRUE, IDD, WS_VISIBLE | WS_CHILD, IDD);
EnableDocking(CBRS_ALIGN_RIGHT | CBRS_ALIGN_LEFT);
AddPane(pane);
DockPane(pane);
This works in that a sidebar window appears, but it doesn't seem to be movable and isn't getting drawn properly.
I feel like I'm shooting in the dark with all this. Does anybody know what the right approach to it is?
|
If we both shoot in the dark, we double our chances of hitting something.
Looking at the documentation for CDockablePane (the parent class of CPaneDialog), I notice a method called EnableGripper. Try that.
|
711,669
| 4,027,195
|
How can I call a .NET form from an MFC application?
|
We have a several large MFC applications which presently call a COM object to bring up a complex dialog. We would like to integrate the dialog into the applications -- we do not want to continue to use a COM object.
I'm investigating the possibility of building the dialog in .NET as a separate project (using Windows forms, not WPF) and providing a second C++/CLI project which calls it and which can be called from ordinary C++ code. This structure is so that the several applications that need to incorporate the dialog can just pick up the projects in their solutions. (The apps are legacy apps, and rewriting them extensively is not possible -- we're slowly moving them to .NET, but this is a multi-year project. Converting the apps to C++/CLI is not an option.)
I've built this and tested it from a model application, but so far I'm unable to get it to work in the simplest of the large apps, and based on some things I've read, I'm beginning to doubt that it is possible. (See this link, especially. I'm aware of this Stackoverflow question, but it does not seem to be relevant.)
So. Is this even possible? Any suggestions on how to proceed?
|
I finally solved this problem with the help of a very good Microsoft support specialist. There were two problems, one was that the Boost library's threading is incompatible with C++/CLI in its default state. One solution is to compile with a different set of flags and then statically link it. The other is to use it as a dynamically linked DLL, which is what I wound up doing.
The second part of the solution is to set CLR threading in the linking property to STA, since OLE initializations fails with an unhelpful message if you don't.
|
711,770
| 712,275
|
Fast implementation of Rolling hash
|
I need a Rolling hash to search for patterns in a file. (I am trying to use the Rabin-Karp string search algorithm).
I understand how a good Hash works and how a good Rolling Hash should work but I am unable to figure out how to efficiently implement the divide (or inverse multiplication) when rolling the hash. I also read rsync uses rolling version of adler32 but that doesn't looks like a random enough hash.
Ideally it will be great if you can point me to an optimized C/C++ implementation, but any pointers in the right direction will help.
|
Cipher's "prime base" idea should work decently - though the solution he posted looks a bit sketchy.
I don't think there's any need for inverse multiplication in this method.
Here's my solution:
Say the string we currently have hashed is "abc", and we want to append "d" and remove "a".
Just like Cipher, my basic hash algorithm will be:
unsigned hash(const string& s)
{
unsigned ret = 0;
for (int i = 0; i < s.size(); i++)
{
ret *= PRIME_BASE; //shift over by one
ret += s[i]; //add the current char
ret %= PRIME_MOD; //don't overflow
}
return ret;
}
Now, to implement sliding:
hash1 = [0]*base^(n-1) + [1]*base^(n-2) + ... + [n-1]
We'd like to add something at the end and remove the first value, so
hash2 = [1]*base^(n-1) + [2]*base^(n-2) + ... + [n]
First we can add the last letter:
hash2 = (hash1 * PRIME_BASE) + newchar;
=> [0]*base^n + [1]*base^(n-1) + ... + [n-1]*base + [n]
Then simply subtract the first character:
hash2 -= firstchar * pow(base, n);
=> [1]*base^(n-1) + ... + [n]
An important note: you have to be careful about overflow. You can choose to just let it overflow unsigned int, but I think it's much more prone to collision (but also faster!)
Here's my implementation:
#include <iostream>
#include <string>
using namespace std;
const unsigned PRIME_BASE = 257;
const unsigned PRIME_MOD = 1000000007;
unsigned hash(const string& s)
{
long long ret = 0;
for (int i = 0; i < s.size(); i++)
{
ret = ret*PRIME_BASE + s[i];
ret %= PRIME_MOD; //don't overflow
}
return ret;
}
int rabin_karp(const string& needle, const string& haystack)
{
//I'm using long longs to avoid overflow
long long hash1 = hash(needle);
long long hash2 = 0;
//you could use exponentiation by squaring for extra speed
long long power = 1;
for (int i = 0; i < needle.size(); i++)
power = (power * PRIME_BASE) % PRIME_MOD;
for (int i = 0; i < haystack.size(); i++)
{
//add the last letter
hash2 = hash2*PRIME_BASE + haystack[i];
hash2 %= PRIME_MOD;
//remove the first character, if needed
if (i >= needle.size())
{
hash2 -= power * haystack[i-needle.size()] % PRIME_MOD;
if (hash2 < 0) //negative can be made positive with mod
hash2 += PRIME_MOD;
}
//match?
if (i >= needle.size()-1 && hash1 == hash2)
return i - (needle.size()-1);
}
return -1;
}
int main()
{
cout << rabin_karp("waldo", "willy werther warhol wendy --> waldo <--") << endl;
}
|
711,779
| 712,221
|
Template Meta-programming with Char Arrays as Parameters
|
I'm playing around with TMP in GCC 4.3.2's half-implementation of C++11, and I was wondering if there was a way to somehow do the following:
template <char x, char... c>
struct mystruct {
...
};
int main () {
mystruct<"asdf">::go();
}
It obviously won't let me do it just like that, and I thought I'd get lucky by using user-defined literals to transform the "asdf" string during compile-time, but GCC 4.3 doesn't support user-defined literals...
Any suggestions? I'd prefer to not do 'a','s','d','f', since this severely hampers my plans for this project.
|
Sadly, you still have to split it into separate characters, eg:
myTemplate<'s','t','r','i','n','g'>
In my humble opinion, this is a huge oversight in the new standard. Some other people agreed, and tried to implement the behavior in GCC with pretty good results. You can find that thread here.
Edit: Some weird problems with the link, so cut and paste from this:
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/9b0edd169ba2ce3c
|
712,279
| 712,307
|
What is the usefulness of `enable_shared_from_this`?
|
I ran across enable_shared_from_this while reading the Boost.Asio examples and after reading the documentation I am still lost for how this should correctly be used. Can someone please give me an example and explanation of when using this class makes sense.
|
It enables you to get a valid shared_ptr instance to this, when all you have is this. Without it, you would have no way of getting a shared_ptr to this, unless you already had one as a member. This example from the boost documentation for enable_shared_from_this:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_from_this();
}
}
int main()
{
shared_ptr<Y> p(new Y);
shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p)); // p and q must share ownership
}
The method f() returns a valid shared_ptr, even though it had no member instance. Note that you cannot simply do this:
class Y: public enable_shared_from_this<Y>
{
public:
shared_ptr<Y> f()
{
return shared_ptr<Y>(this);
}
}
The shared pointer that this returned will have a different reference count from the "proper" one, and one of them will end up losing and holding a dangling reference when the object is deleted.
enable_shared_from_this has become part of C++ 11 standard. You can also get it from there as well as from boost.
|
712,282
| 712,292
|
enqueue() method adds one element to the queue: how to implement in C++?
|
I'm having a hard time trying to implement this method since array subscripts in C++ start with zero. The method add one element to the queue. You can use f (front) and r (rear) pointers and a sequential list of size n. If you find that additional variables are needed fell free. Thanks.
Thats my try but I know its wrong:
void QueueAr::enqueue(const Object& x){
prov = (r % n) + 1;
if(prov != f){
r = prov;
queueArray[r] = x;
if(f = -1){
f = 0
}
}else{
//queue is full
}
}
How do I work with the pointers? If I start them pointing to NULL I cant use pointer arithmetic.
|
To implement a queue using plain arrays, just treat it circularly - so as soon as you run out of space in the array, wrap back around to 0. You'll need to keep a record of front and rear, as you note. As an example (where X represents an item in the queue):
// Rear is where to enqueue into, Front is where to dequeue from
Empty Array:
| - - - |
Front = -1, Rear = 0
Enqueue()
| X - - |
Front = 0, Rear = 1
Enqueue()
| X X - |
Front = 0, Rear = 2
Dequeue()
| - X - |
Front = 1, Rear = 2
Enqueue()
| - X X |
Front = 1, Rear = 0 // Looped around
Dequeue()
| - - X |
Front = 2, Rear = 0
Enqueue()
| X - X |
Front = 2, Rear = 1
You just have to use modular arithmetic to wrap around. Of course, this is limited in size (once you run out of elements, you'd have to allocate more memory), but that's just what you get when dealing with arrays.
Here's some code as a start (I haven't checked it at all):
// Private class variables:
// These should be set in the constructor of your queue class
unsigned int rear = 0; // back of the queue
unsigned int front = -1; // front of the queue
unsigned int numStored = 0;
unsigned int length;
Object* array = new Object[length];
QueueAr::Enqueue(Object& obj)
{
if (front == rear)
{
// Throw an exception: queue is full!
}
else
{
array[rear] = obj; // Insert the object at the back
rear++;
rear = rear % length;
numStored++;
}
}
// For kicks, here's the queue code
QueueAr::Dequeue(Object& obj)
{
if (numStored == 0)
{
// Throw an exception: queue is empty!
}
front++;
front = front % length;
numStored--;
}
|
712,334
| 712,349
|
Does the evil cast get trumped by the evil compiler?
|
This is not academic code or a hypothetical quesiton. The original problem was converting code from HP11 to HP1123 Itanium. Basically it boils down to a compile error on HP1123 Itanium. It has me really scratching my head when reproducing it on Windows for study. I have stripped all but the most basic aspects... You may have to press control D to exit a console window if you run it as is:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char blah[6];
const int IAMCONST = 3;
int *pTOCONST;
pTOCONST = (int *) &IAMCONST;
(*pTOCONST) = 7;
printf("IAMCONST %d \n",IAMCONST);
printf("WHATISPOINTEDAT %d \n",(*pTOCONST));
printf("Address of IAMCONST %x pTOCONST %x\n",&IAMCONST, (pTOCONST));
cin >> blah;
return 0;
}
Here is the output
IAMCONST 3
WHATISPOINTEDAT 7
Address of IAMCONST 35f9f0 pTOCONST 35f9f0
All I can say is what the heck? Is it undefined to do this? It is the most counterintuitive thing I have seen for such a simple example.
Update:
Indeed after searching for a while the Menu Debug >> Windows >> Disassembly had exactly the optimization that was described below.
printf("IAMCONST %d \n",IAMCONST);
0024360E mov esi,esp
00243610 push 3
00243612 push offset string "IAMCONST %d \n" (2458D0h)
00243617 call dword ptr [__imp__printf (248338h)]
0024361D add esp,8
00243620 cmp esi,esp
00243622 call @ILT+325(__RTC_CheckEsp) (24114Ah)
Thank you all!
|
Looks like the compiler is optimizing
printf("IAMCONST %d \n",IAMCONST);
into
printf("IAMCONST %d \n",3);
since you said that IAMCONST is a const int.
But since you're taking the address of IAMCONST, it has to actually be located on the stack somewhere, and the constness can't be enforced, so the memory at that location (*pTOCONST) is mutable after all.
In short: you casted away the constness, don't do that. Poor, defenseless C...
Addendum
Using GCC for x86, with -O0 (no optimizations), the generated assembly
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $36, %esp
movl $3, -12(%ebp)
leal -12(%ebp), %eax
movl %eax, -8(%ebp)
movl -8(%ebp), %eax
movl $7, (%eax)
movl -12(%ebp), %eax
movl %eax, 4(%esp)
movl $.LC0, (%esp)
call printf
movl -8(%ebp), %eax
movl (%eax), %eax
movl %eax, 4(%esp)
movl $.LC1, (%esp)
call printf
copies from *(bp-12) on the stack to printf's arguments. However, using -O1 (as well as -Os, -O2, -O3, and other optimization levels),
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $20, %esp
movl $3, 4(%esp)
movl $.LC0, (%esp)
call printf
movl $7, 4(%esp)
movl $.LC1, (%esp)
call printf
you can clearly see that the constant 3 is used instead.
If you are using Visual Studio's CL.EXE, /Od disables optimization. This varies from compiler to compiler.
Be warned that the C specification allows the C compiler to assume that the target of any int * pointer never overlaps the memory location of a const int, so you really shouldn't be doing this at all if you want predictable behavior.
|
712,623
| 712,633
|
How do you use an exponent in c++ with a variable?
|
So I realize that #include is necessary, and that there is a pow(x,y) where x^y works...but when I attempted to use pow(2,(num-1)), it kicked back an error...
errorC2668: 'pow' : ambiguous call to overloaded function
the line of code I have for it is as follows
perfect = (pow(2,(num-1))) * (pow(2,num)-1);
Any recommendations?
Thanks in advance
EDIT:
num is indeed declared as an int.
num does have a value, starts at 1 and goes to UINT_MAX
Added an asterisk to equation
|
The compiler doesn't know which pow() function to call. The overloads listed here gives the following list:
float pow ( float base, float exponent );
double pow ( double base, double exponent );
long double pow ( long double base, long double exponent );
float pow ( float base, int exponent );
double pow ( double base, int exponent );
long double pow ( long double base, int exponent );
The compiler won't guess which one to use. Make it explicit with a casts.
perfect = (pow(2.,(double)(num-1))) < (pow(2.,(double)num)-1);
There may be some extra casts there, but they won't hurt anything.
|
712,691
| 712,712
|
Registering implementation of a COM interface
|
I'm new to COM programming. I've got a COM object (and associated IClassFactory) all ready to go, but I can't quite figure out how to go about registering the resulting DLL for use by other programs. The number of GUIDs I need to sling around is also unclear to me.
The COM object I'm trying to register implements the IAudioSessionEvents interface.
I have come across the DllRegisterServer and DllUnregisterServer functions, but I haven't found any clear demonstrations of their usage. What keys do they deal with, how are they invoked, by what and when, etc.?
Thanks,
-Kevin Montrose
|
I'm not sure from this post whether you are implementing or consuming the DLL that supports IAudioSessionEvents. If you're consuming this DLL, then you can register the component using the comment line utility regsvr32. To register use:
regsvr32
To unregister:
regsvr32 /u
regsvr32 should be on your path, so this command will work from any directory.
If you are implementing the DLL in question, then you must provide an implementaion of the DllRegisterServer and DllUnRegisterServer functions. These functions must set up and clean up registry entries for your component. The purpose of the registry entries is to provide a ProgID, map it to a CLSID, and provid interface ID for the interfaces that the component supports. For example, the interface ID for IAudioSessionEvent. If you're implementing the DLL, you'll have to provide code to perform all of these tasks.
Note: these functions are called by regsvr32 in order to register the component.
If very unusual to actually write this code, generally you'll want to use a framework like ATL, which takes care of the busywork for you. It is a good exercise to write this code at least once if you really want to know COM from the ground up.
|
712,737
| 713,204
|
Callback Routine Not Getting Triggered
|
I've created a very simple one-button MFC dialog app that attempts to utilize a callback function. The app complies and runs just fine, but the callback routine never gets triggered.
What needs to be modified in order to get the callback to trigger properly?
You can download the test.zip file here (the test app is in VS 2003 to ensure more people can try it out): http://tinyurl.com/testfile-zip
The code utilizes an alarm class on CodeProject, and the callback function is suppsed to get triggered every 3 seconds (as determined by the code being passed in).
Thanks!
|
I've looked at your code and the I believe the Function called from the button is the problem
void CTestDlg::OnBnClickedButton1()
{
CAlarmClock clock;
REPEAT_PARMS rp;
ZeroMemory(&rp, sizeof(REPEAT_PARMS));
rp.bRepeatForever = TRUE;
rp.Type = Repeat_Interval;
rp.ss = 3;
clock.SetRepeatAlarm(0, 0, 0, rp, CallbackRtn);
}
This creates the Alarm clock on the function stack.
This CAlarmclock object is therefore destroyed at the end of the function along with its contents.
For it to be able to exist for long enough to actually do the callback
you need to add it as a member variable of your dialog class for it to exist and callback for as long as the dialog exists.
See the example code on the CAlarmclock codeproject page for how to use this class correctly.
|
712,975
| 734,293
|
How to track memory leaks with umdh.exe in all heaps?
|
I have a c++ windows application that leaks memory per transaction. Using perfmon I can see the private bytes increase with every transaction, the memory usage is flat while the application is idle.
Following previous answers on stackoverflow I used umdh from the microsoft debugging tools to track down one memory leak. However there is still more leaks and the results of umdh don't match up with my perfmon results.
First umdh does still reports this leak, the stack trace is:
+ 36192 ( 2082056 - 2045864) 251 allocs BackTraceCB
+ 4 ( 251 - 247) BackTraceCB allocations
ntdll!RtlAllocateHeapSlowly+00000041
ntdll!RtlAllocateHeap+00000E9F
MSVCR80!malloc+0000007A
This is no use as the first call is malloc, it doesn't say what called it. I have my doubts about this leak as it is reported both when the application is processing transactions and when it is idle. But I can clearly see that no memory is leaking when it is idle. And the memory leaks reported when processing the transactions are not proportional to the transactions processed as perfmon reports.
umhd does not show any other leaks, although I know there is at least one more not shown. I have just learn from searching the net that a windows application can have multiple heaps.
Could it be that umhd only reports memory usage from one of these heap? eg the default or crt heap?
How can I track memory usage in other heaps?
And how do find out what dlls / modules are using the other heaps?
Any pointers to tracking down this problem would be gratefully received as I am running out of options.
|
Sorry to answer my own question, but I finally tracked the issue down to how I used Orbix.
It seams that the orbix libraries use their own heap on the windows platform. This means that most memory leak detection does not work for leaks in orbix, I tried boundschecker and umhd.exe.
To isolate this issue I found some code that would dump the memory of each heap in the application: http://www.abstraction.net/content/articles/analyzing%20the%20heaps%20of%20a%20win32%20process.htm
I used this to dump the heap usage before and after each transaction, then after every 500 transactions, this indicated that the same heap was growing each time. Then I listed the the address of each entry in this heap. Examining the memory in these areas I found that these contained orbix marshalling data. With this information I finally found a some object references that were not being cleaned up.
|
712,998
| 13,615,449
|
OpenCV with Network Cameras
|
I'm using openCV 1.1pre1 under Windows.
I have a network camera and I need to grab frames from openCV. That camera can stream a standard mpeg4 stream over RTSP or mjpeg over http.
I've seen many threads talking about using ffmpeg with openCV but I cannot make it work.
How I can grab frames from an IP camera with openCV?
Thanks
Andrea
|
rtsp protocol did not work for me.
mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).
Syntax found here:
http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/
I did not need to compile OpenCV with ffmpg support.
|
713,042
| 713,052
|
Should "portable" C compile as C++?
|
I got a comment to an answer I posted on a C question, where the commenter suggested the code should be written to compile with a C++ compiler, since the original question mentioned the code should be "portable".
Is this a common interpretation of "portable C"? As I said in a further comment to that answer, it's totally surprising to me, I consider portability to mean something completely different, and see very little benefit in writing C code that is also legal C++.
|
No. My response Why artificially limit your code to C? has some examples of standards-compliant C99 not compiling as C++; earlier C had fewer differences, but C++ has stronger typing and different treatment of the (void) function argument list.
As to whether there is benefit to making C 'portable' to C++ - the particular project which was referenced in that answer was a virtual machine for a traits based language, so doesn't fit the C++ object model, and has a lot of cases where you are pulling void* of the interpreter's stack and then converting to structs representing the layout of built-in object types. To make the code 'portable' to C++ it would have add a lot of casts, which do nothing for type safety.
|
713,309
| 713,479
|
C++ STL: Can arrays be used transparently with STL functions?
|
I was under the assumption that STL functions could be used only with STL data containers (like vector) until I saw this piece of code:
#include <functional>
#include <iostream>
#include <numeric>
using namespace std;
int main()
{
int a[] = {9, 8, 7};
cerr << "Sum: " << accumulate(&a[0], &a[3], 0, plus<int>()) << endl;
return 0;
}
It compiles and runs without any warnings or errors with g++, giving the correct output sum of 24.
Is such usage of arrays with STL functions allowed by the C++/STL standard? If yes, how do archaic structures like arrays fit into the grand STL plan of templated iterators, containers and functions? Also, are there any caveats or details in such usage that the programmer should be careful about?
|
Well, you ask about an array. You can just easily get a pointer to its elements, so it basically boils down to the question whether pointers can be used transparently with STL functions. A pointer actually is the most powerful kind of an iterator. There are different kinds
Input iterator: Only forward and one-pass, and only read
Output iterator: Only forward and one-pass, and only write
Forward iterator: Only forward, and read/write
Bidirectional iterator: Forward and backward, and read/write
Random access iterator: Arbitrary steps forward and backward in one breath, and read/write
Now each iterator in the second group supports all the things of all iterators mentioned before it. A pointer models the last kind of iterators - a random access iterator. You may add/subtract an arbitrary integer and you may read and write. And all except the output iterator has a operator-> that can be used to access a member of the element type we iterate over.
Normally, iterators have several typedefs as members
value_type - what the iterator iterates over (int, bool, string, ...)
reference - reference to the value_type
pointer - pointer to the value_type
difference_type - what type the distance between two iterators has (returned by std::distance).
iterator_category - this is a tag-type: it is typedefed to a type that represents the kind of the iterator. either std::input_iterator_tag, ..., std::random_access_iterator_tag. Algorithms can use it to overload on different kinds of iterators (like std::distance is faster for random access iterators, because it can just return a - b)
Now, a pointer of course does not have those members. C++ has an iterator_traits template and specializes it for pointers. So if you want to get the value type of any iterator, you do
iterator_traits<T>::value_type
And whether it is a pointer or some other iterator, it will give you the value_type of that iterator.
So - yes, a pointer can very well be used with STL algorithms. As someone else mentioned, even std::vector<T>::iterator can be a T*. A pointer is a very good example of an iterator even. Because it is so exceedingly simple but at the same time so powerful that it can iterate over a range.
|
713,698
| 713,717
|
C++ namespaces advice
|
I'm just teaching myself C++ namespaces (coming from a C# background) and I'm really starting to think that even with all the things that C++ does better than most other languages, nested namespaces isn't one of them!
Am I right in thinking that in order to declare some nested namespaces I have to do the following:
namespace tier1
{
namespace tier2
{
namespace tier3
{
/* then start your normal code nesting */
}
}
}
As opposed to:
namespace tier1::tier2::tier3
{
}
à la C#?
This becomes even more demented when I need to forward declare:
namespace tier1
{
namespace tier2
{
namespace forward_declared_namespace
{
myType myVar; // forward declare
}
namespace tier3
{
/* then start your normal code nesting */
class myClass
{
forward_declared_namespace::myType myMember;
}
}
}
}
Bearing in mind that a typical system that I develop consists of:
MyCompany::MySolution::MyProject::System::[PossibleSections]::Type
Is this why you don't tend to see much use of namespaces in C++ examples? Or usually only single (not nested) namespaces?
UPDATE
For anyone interested, this is how I ended up tackling this issue.
|
C++ namespaces were not intended to be a design mechanism - they are there simply to prevent name clashes. You really don't want or need to use nested namespaces in 99.99% of situations.
A good example of the correct use of namespaces in C++ is the C++ Standard Library. Everything in this quite large library is placed in a single namespace called std - there is no attempt or need to break the library up into (for example) an I/O sub-namespace, a math sub-namespace, a container sub-namespace etc.
The basic tool for modelling in C++ is the class (and to some extent the template), not the namespace. If you feel the need for nesting, you should consider using nested classes, which have the following advantages over namespaces:
they have methods
they can control access
they cannot be re-opened
Having considered these, if you still wish to use nested namespaces by all means do so - there is nothing technically wrong with using them in this way.
|
713,701
| 750,479
|
Force-directed layout implementation in C++
|
Are you aware of an open source implementation of force-directed layout in C++ used for GUIs? Preferably BSD/MIT/Apache or other (non-GPL) license.
|
The excellent Boost.Graph library provides a wide range of algorithms, among which a few layout algorithms. I'd recommend using either Kamada-Kawai spring layout or Fruchterman-Reingold force-directed layout.
Boost licence is very permissive so don't worry about that.
|
713,704
| 713,735
|
C++ as a first language
|
I've been self-learning C++ for about 4 months now. I'm enjoying it, and I think I'm doing quite well. However, an answer to a question of mine got me thinking that I might be setting myself up for a fall.
So, what do people here think about C++ as a first language to learn? And is it worth me just carrying on now that I've made a good start?
|
I don't understand why people still confuse "language" with "library". (Referring to the linked answer.) So what if C++ doesn't have a "native" concept of audio? There are lots of libraries out there, which you can readily use with C++, and which are probably better suited to your specific needs than any "catch-all" "standard-library" audio processing API could be.
</rant>
C++ is a difficult language. There are others that are easier to learn. I would never argue about that.
But C++ is easily one of the most powerful languages around. It can be highly efficient, and highly elegant, at once. Of course, nothing keeps you from making a fine big mess of everything, either.
If I recommend C++ as a first programming language? Actually, I don't know any better. Others might protect you from making mistakes, and make initial success (e.g. your first GUI application) easier. But if you build on a foundation of C++, you will always be on a secure footing. You might never have to chose another language at all, actually. But if you want / have to, you will find it ridiculously easy.
An experienced C++ coder can do e.g. Java at full speed in a matter of weeks. The other way round? Much, much more difficult.
Many years later, I felt like I should amend this answer. Since my kids asked me to teach them programming, I started to do so. I found myself actually not starting with C++... because I showed them BF first. In absolutely no time at all, they understood about memory and pointers. Then I went on with C++, and we're enjoying ourselves immensely so far.
Yet some more years later, and I felt I really should add this excellent lecture by Kate Gregory from CppCon 2015 to this answer:
Stop Teaching C.
|
713,797
| 713,820
|
Naming functions, methods, pointers, variables, arrays etc in C++
|
Allright, doing some project with few friends, and I need some standard for naming things in c++. Does anyone have any good naming scheme for c++ that is well thought-out and not made in like 10min.
Example, int* house should be named int* house_p, so that when someone reads the code, he doesn't need to scroll all the time wondering if a thing is a pointer, array, matrix, or whatever...
Post your well thought-out naming schemes that you are using !
|
Example, int* house should be named
int* house_p, so that when someone
reads the code, he doesn't need to
scroll all the time wondering if a
thing is a pointer, array, matrix, or
whatever...
But what if its type changes - are you going to go through all your code and change the names of all the variables. And what if the variable is an instance of a complex type:
ComplicatedDerivativeFinancialInstrument x;
What suffix will you use?
What you are asking about is known as Hungarian notation - its use in C++ is almost universally considered to be A Bad Idea.
|
714,142
| 714,228
|
JPEG Quality when creating a JPEG in Carbon
|
I'm writing a Carbon application and we are creating JPEG files. I'm currently doing this by using Quartz CGImageDestinations and kCGImagePropertyJFIFDictionary. However, JFIF doesn't seem to have any entry for compression quality. Does anyone know how to set this?
thanks
|
This is separate from the JFIF options, since some other formats (including TIFF) support lossy compression. The key you use is kCGImageDestinationLossyCompressionQuality, and you put this option and the JFIF-options dictionary into the same dictionary; you don't put it into the JFIF-options dictionary.
|
714,205
| 714,218
|
How does the draggable crosshair in Process Explorer work?
|
There is a feature in Sysinternal's Process Explorer that allows a crosshair to be dragged from the application to a control in any other application you are running and highlights said control.
Does anyone know how this was achieved or if there is a .NET/C++ library out there that can be reused?
|
Using Win32 API
GetCursorPos: to get the cursor position (maybe .NET has its own function to do that)
WindowFromPoint: to get the handle of the window from a specific point in the screen
more info
|
714,213
| 714,289
|
c++ template casting
|
I'm a little lost in how to cast templates. I have a function foo which takes a parameter of type ParamVector<double>*. I would like to pass in a ParamVector<float>*, and I can't figure out how to overload the casting operator for my ParamVector class, and Google isn't helping me that much. Does anyone have an example of how to do this? Thanks.
EDIT: Adding some code, sorry I'm an idiot and didn't phrase the original question well at all;
template<class T> class ParamVector
{
public:
vector <T> gnome;
vector <T> data_params;
}
template<class T> class ParamVectorConsumer
{
public:
ParamVector<T> test;
}
ParamVector<float> tester;
ParamVectorConsumer<double> cons;
cons.ParamVector = tester
will fail to compile. I would like to know how to write it so that I can cast the float version of tester to a ParamVector double. Thanks
EDIT2: Casting was the wrong word. I don't mind writing extra code, I just need to know how to get this to be accepted by the compiler so that I can write some sort of conversion code.
|
I'm not sure but maybe you need some like this:
template< typename TypeT >
struct ParamVector
{
template < typename NewTypeT >
operator ParamVector< NewTypeT >()
{
ParamVector< NewTypeT > result;
// do some converion things
return result;
}
template< typename NewTypeT >
ParamVector( const ParamVector< NewTypeT > &rhs )
{
// convert
}
template < typename NewTypeT >
ParamVector& operator=( const ParamVector< NewTypeT > &rhs )
{
// do some conversion thigns
return *this;
}
};
ParamVector< double > d1;
ParamVector< float > f1;
f1 = d1;
You can choose use conversion operator or operator= - I've provided both in my example.
|
715,139
| 715,190
|
Why would you cast the lhs of an assignment?
|
I came across some code that boils down to the following:
enum BAR { /* enum values omitted */ }
class Foo{
public:
void set(const BAR& bar);
private:
uint32_t bits;
};
void Foo::set(const BAR& bar)
{
(uint32_t&)bits = bits | bar;
}
I don't understand the point of the c-style cast in the assignment in Foo::set. Why would you cast the lhs of an assignment? Am I crazy, or does this have a purpose?
|
In this case, I can't see any reason for the cast, as the thing being cast is of the same type as the cast. In general, it could be used to force a particular assignement operator to be used.
I will now repeat my mantra: If your code contains casts, there is probably something wrong with the code or the design and you should examine both with a view to removing the cast.
|
715,530
| 715,544
|
Unit testing and mocking small, value-like classes in C++
|
I am trying to set up some unit tests for an existing c++ project.
Here's the setup:
I have chosen Google Mock, which includes Google Test. I have added another project (called Tests) to the Visual Studio Solution. The units to test are in another project called Main. The plan is to add each cpp file that I want to test to the Tests project. The Tests project has access to all header files from Main.
I have added one cpp file to the Tests project, and it compiles, but comes up with linker errors. Most are because of a class derived from COleDateTime, called CTimeValue. The unit under test has methods with pass-by-value CTimeValue parameters and also declares some CTimeValue attributes.
I want to test the UUT in isolation, and use mocks and fakes for all dependencies. I don't see how to do it with CTimeValue. It is used as a value, contains no virtual methods, but is still quite complex and would deserve a seperate unit test.
CTimeValue is only one of many classes that is like this in the project. How can I isolate the testing of classes that use these user-defined types?
Cheers, Felix
|
Sometimes one can not simply mock things. In that case what you can do is have a comprehensive test for the class in question (CTimeValue) and make sure you run the tests for that class as a subsuite in your other test.
|
715,823
| 715,907
|
Print bit representation of a string
|
How to print the bit representation of a string
std::string = "\x80";
void print (std::string &s) {
//How to implement this
}
|
I'd vote for bitset:
void pbits(std::string const& s) {
for(std::size_t i=0; i<s.size(); i++)
std::cout << std::bitset<CHAR_BIT>(s[i]) << " ";
}
int main() {
pbits("\x80\x70");
}
|
715,919
| 715,936
|
Member function vs. nonmember function?
|
What is your rule for which functions that operate on a class should be member functions vs. nonmember functions?
For example, I have a class which represents a maze using a matrix of bools. I am making a function called isConnected which verifies that 2 points in the maze are in the same region (i.e. it is possible to travel from A to B).
Should this be member or nonmember? What is a good rule?
|
When to make it a member function:
when the function is logically coupled with the class (like your maze connectedness example)
when the function needs to access private or protected members, it's better to make it a member than a friend.
When to make it a standalone function
when it's a generic function that can be templatized to naturally work on other classes (look at the <algorithms> header for good example)
|
715,920
| 716,119
|
Qt: QGraphicsScene not updating when I would expect it to
|
Ok so I've got a QGraphicsScene in a class called eye. I call a function:
void eye::playSequence(int sequenceNum) {
for (int i=0; i<sequences[sequenceNum].numberOfSlides(); i++) {
presentSlide(sequenceNum, i);
time_t start;
time(&start);
bool cont=false;
while (!cont) {
time_t now;
time(&now);
double dif;
dif=difftime(now, start);
if (dif>5.0)
cont=true;
}
}
}
which for each slide calls:
void eye::presentSlide(int sequenceNum, int slideNum) {
Slide * slide=sequences[sequenceNum].getSlide(slideNum);
QGraphicsPixmapItem * pic0=scene.addPixmap(slide->getStimulus(0)->getImage());
pic0->setPos(0,0);
QGraphicsPixmapItem * pic1=scene.addPixmap(slide->getStimulus(1)->getImage());
pic1->setPos(horizontalResolution-350,0);
QGraphicsPixmapItem * pic2=scene.addPixmap(slide->getStimulus(2)->getImage());
pic2->setPos(horizontalResolution-350,verticalResolution-450);
QGraphicsPixmapItem * pic3=scene.addPixmap(slide->getStimulus(3)->getImage());
pic3->setPos(0,verticalResolution-450);
}
Now, I would expect this to display one set of images, wait for 5 seconds, then display the next, and so on. Instead, it displays nothing until all the slides have been processed and then the last four images are displayed. I've tried calling scene.update() in every place I could image and it didn't do anything. It seems like the scene only updates when the playSequence function returns. Any ideas what might be going on here?
|
This is the kind of behaviour that is often seen in event driven GUI frameworks when one wants to do continuous animation. I'm going to guess that eye::playSequence is called from a button click or maybe from some point during the application startup code? In any case, here is what's going on.
Qt uses the main application thread to drive an event loop. The event loop is something like this:
while(app_running)
{
if(EventPending)
ProcessNextEvent();
}
The problem you are seeing is that updates to the screen are done during a paint event. If you are running some code during a mouse click event or any other event, then all the drawing you are doing is queued up and will be drawn to the screen on the next paint event. Sometimes it takes awhile for this to sink in.
The best way to address this is to change your approach a bit. One way is to throw away your while loop and setup a QTimer set to fire every 5 seconds. In the timer slot you can draw one slide. When the timer fires again, draw the next slide, etc.
If you want a more direct and less elegant quick fix, try calling qapp->processEvents() right after your call to presentSlide(sequenceNum, i). This (most of the time) will force the application to clear out any queued up events which should include paint events.
I should also mention that eye::presentSlide() is merely adding new scene objects to the scene on each iteration covering the ones that were added during the last call. Think of the scene as a fridge door and when you call scene().addXXX you are throwing more fridge magnets on the door :)
|
716,353
| 716,362
|
Must new always be followed by delete?
|
I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program
int main()
{
int* arr = new int[5];
return 0;
}
While for all intents and purposes no leak occurs here (since your program is ending and the OS will clean up all memory once it returns), but does the standard still require -- or recommend -- the usage of delete[] in this case? If not, would there be any other reason why you would delete[] here?
|
There is nothing that requires a delete[] in the standard - However, I would say it is a very good guideline to follow.
However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination.
Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete guarantees the destruction in these cases.
Also, if you ever move around your routines, you are less likely to cause memory leaks in other places in your code.
|
716,658
| 716,726
|
Overloading = in C++
|
I'm trying to overload the assignment operator and would like to clear a few things up if that's ok.
I have a non member function, bool operator==( const MyClass& obj1, const myClass& obj2 ) defined oustide of my class.
I can't get at any of my private members for obvious reasons.
So what I think I need to do is to overload the assignment operator. And make assignments in the non member function.
With that said, I think I need to do the following:
use my functions and copy information using strcpy or strdup. I used strcpy.
go to the assignment operator, bool MyClass::operator=( const MyClass& obj1 );
Now we go to the function overloading (==) and assign obj2 to obj1.
I don't have a copy constructor, so I'm stuck with these:
class Class
{
private:
m_1;
m_2;
public:
..
};
void Class::Func1(char buff[]) const
{
strcpy( buff, m_1 );
return;
}
void Class::Func2(char buff[]) const
{
strcpy( buff, m_2 );
return;
}
bool Class& Class::operator=(const Class& obj)
{
if ( this != &obj ) // check for self assignment.
{
strcpy( m_1, obj.m_1 );
// do this for all other private members.
}
return *this;
}
bool operator== (const Class& obj1, const Class& obj2)
{
Class MyClass1, MyClass2;
MyClass1 = obj1;
MyClass2 = obj2;
MyClass2 = MyClass1;
// did this change anything?
// Microsofts debugger can not get this far.
return true;
}
So as you can probably tell, I'm completely lost in this overloading. Any tips? I do have a completed version overloading the same operator, only with ::, so my private members won't lose scope. I return my assignments as true and it works in main. Which is the example that I have in my book.
Will overloading the assignment operator and then preforming conversions in the operator== non member function work? Will I then be able to assign objects to each other in main after having completed that step?
|
I am guessing that you want to compare the two objects. In that case, you can just overload the operator == in class "Class". You don't need assignment operator.
class Class
{
public:
Class(int i) : m_i(i){}
bool operator==( const Class& rhs)
{
return m_i == rhs.m_i;
}
private:
int m_i;
};
int main()
{
Class t1(10), t2(10);
bool b = (t1 == t2);
}
|
716,762
| 716,769
|
C++ STL: Which method of iteration over a STL container is better?
|
This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?
class Elem;
typedef vector<Elem> ElemVec;
ElemVec elemVec;
// Method 0
for (ElemVec::iterator i = elemVec.begin(); i != elemVec.end(); ++i)
{
Elem& e = *i;
// Do something
}
// Method 1
for (int i = 0; i < elemVec.size(); ++i)
{
Elem& e = elemVec.at(i);
// Do something
}
Method 0 seems like cleaner STL, but Method 1 achieves the same with lesser code. Simple iteration over a container is what appears all over the place in any source code. So, I'm inclined to pick Method 1 which seems to reduce visual clutter and code size.
PS: I know iterators can do much more than a simple index. But, please keep the reply/discussion focused on simple iteration over a container like shown above.
|
The first version works with any container and so is more useful in template functions that take any container a s a parameter. It is also conceivably slightly more efficient, even for vectors.
The second version only works for vectors and other integer-indexed containers. It'd somewhat more idiomatic for those containers, will be easily understood by newcomers to C++, and is useful if you need to do something else with the index, which is not uncommon.
As usual, there is no simple "this one is better" answer, I'm afraid.
|
716,810
| 716,846
|
BOOST_FOREACH: What is the error on using this of a STL container?
|
Does anyone know why the following generates an error on VC9?
class Elem;
class ElemVec : public vector<Elem>
{
public:
void foo();
};
void ElemVec::foo()
{
BOOST_FOREACH(Elem& elem, *this)
{
// Do something with elem
}
return;
}
The error I get is:
error C2355: 'this' : can only be referenced inside non-static member functions
The only (hack) solution I have right now which compiles without error is:
void ElemVec::foo()
{
ElemVec* This = this;
BOOST_FOREACH(Elem& elem, *This)
{
// Do something with elem
}
return;
}
|
Which compiler/Boost version are you using? I can compile the following without any problem (VS2005/Boost 1.38):
#include <boost/foreach.hpp>
using namespace std;
struct xxx : std::vector<int>
{
void test()
{
BOOST_FOREACH(int x, *this)
{
}
}
};
int main(void) {
xxx x;
x.test();
return 0;
}
Search the Boost bugbase if you want more details.
|
716,865
| 716,871
|
C++ Boost: Any gotchas with BOOST_FOREACH?
|
This one is for Boost experts. Are there any gotchas or details that the programmer needs to be aware of before he goes in and replaces all his old C/C++ style loops with the lean-and-mean-looking BOOST_FOREACH?
(This question is partly derived from here.)
|
Take a look at:
The Conditional Love article for an understanding of the rationale
The Pitfalls section of documentation
The Portability section just in case you are developing cross-platform products
The bugs page for BOOST_FOREACH
|
716,904
| 716,924
|
Preparing for the next C++ standard
|
The spate of questions regarding BOOST_FOREACH prompts me to ask users of the Boost library what (if anything) they are doing to prepare their code for portability to the proposed new C++ standard (aka C++0x). For example, do you write code like this if you use shared_ptr:
#ifdef CPPOX
#include <memory>
#else
#include "boost/shared_ptr.hpp"
#endif
There is also the namespace issue - in the future, shared_ptr will be part of the std, namespace - how do you deal with that?
I'm interested in these questions because I've decided to bite the bullet and start learning boost seriously, and I'd like to use best practices in my code.
Not exactly a flood of answers - does this mean it's a non-issue? Anyway, thanks to those that replied; I'm accepting jalfs answer because I like being advised to do nothing!
|
The simple answer is "do nothing". Boost is not going to remove the libraries that got adopted into 0x. So boost::shared_ptr will still exist. So you don't need to do anything to maintain portability.
Of course, once 0x is here, a lot of code can be simplified, cleaned up and optimized, but since it's not yet here, that work can't really begin. All you can do is make sure your code will still compile when 0x hits... and it should, just like that. Boost isn't going to delete half their libraries. (I'm not guessing. They've stated this on their mailing list before)
(and if you want to switch to the standard shared_ptr, I'd say it's probably easier to just do a simple search/replace when the time comes. Replace #include <boost/shared_ptr.hpp> with #include <memory>, and boost::shared_ptr with std::shared_ptr)
Or of course, you can just decide on the project that you're going to keep using Boost's shared_ptr. Just because it's been added to the standard library doesn't mean you have to use it, after all.
|
717,004
| 717,050
|
Exception handling aware of execution flow
|
Edit:
For personn interested in a cleaner way to implemenent that, have a look to that answer.
In my job I often need to use third-made API to access remote system.
For instance to create a request and send it to the remote system:
#include "external_lib.h"
void SendRequest(UserRequest user_request)
{
try
{
external_lib::Request my_request;
my_request.SetPrice(user_request.price);
my_request.SetVolume(user_request.quantity);
my_request.SetVisibleVolume(user_request.quantity);
my_request.SetReference(user_request.instrument);
my_request.SetUserID(user_request.user_name);
my_request.SetUserPassword(user_request.user_name);
// Meny other member affectations ...
}
catch(external_lib::out_of_range_error& e)
{
// Price , volume ????
}
catch(external_lib::error_t& e)
{
// Here I need to tell the user what was going wrong
}
}
Each lib's setter do checks the values that the end user has provided, and may thow an exception when the user does not comply with remote system needs. For instance a specific user may be disallowed to send a too big volume. That's an example, and actually many times users tries does not comply: no long valid instrument, the prices is out of the limit, etc, etc.
Conseqently, our end user need an explicit error message to tell him what to modify in its request to get a second chance to compose a valid request. I have to provide hiim such hints
Whatever , external lib's exceptions (mostly) never specifies which field is the source
of aborting the request.
What is the best way, according to you, to handle those exceptions?
My first try at handling those exceptions was to "wrap" the Request class with mine. Each setters are then wrapped in a method which does only one thing : a try/catch block. The catch block then throws a new exceptions of mine : my_out_of_range_volume, or my_out_of_range_price depending on the setter. For instance SetVolume() will be wrapped this way:
My_Request::SetVolume(const int volume)
{
try
{
m_Request.SetVolume(volume);
}
catch(external_lib::out_range_error& e)
{
throw my_out_of_range_volume(volume, e);
}
}
What do you think of it? What do you think about the exception handling overhead it implies? ... :/
Well the question is open, I need new idea to get rid of that lib constraints!
|
If there really are a lot of methods you need to call, you could cut down on the code using a reflection library, by creating just one method to do the calling and exception handling, and passing in the name of the method/property to call/set as an argument. You'd still have the same amount of try/catch calls, but the code would be simpler and you'd already know the name of the method that failed.
Alternatively, depending on the type of exception object that they throw back, it may contain stack information or you could use another library to walk the stack trace to get the name of the last method that it failed on. This depends on the platform you're using.
|
717,239
| 717,251
|
io_service, why and how is it used?
|
Trying to learn asio, and I'm following the examples from the website.
Why is io_service needed and what does it do exactly? Why do I need to send it to almost every other functions while performing asynchronous operations, why can't it "create" itself after the first "binding".
|
Asio's io_service is the facilitator for operating on asynchronous functions. Once an async operation is ready, it uses one of io_service's running threads to call you back. If no such thread exists it uses its own internal thread to call you.
Think of it as a queue containing operations. It guarantees you that those operations, when run, will only do so on the threads that called its run() or run_once() methods, or when dealing with sockets and async IO, its internal thread.
The reason you must pass it to everyone is basically that someone has to wait for async operations to be ready, and as stated in its own documentation io_service is ASIO's link to the Operating System's I/O service so it abstracts away the platform's own async notifiers, such as kqueue, /dev/pool/, epoll, and the methods to operate on those, such as select().
Primarily I end up using io_service to demultiplex callbacks from several parts of the system, and make sure they operate on the same thread, eliminating the need for explicit locking, since the operations are serialized. It is a very powerful idiom for asynchronous applications.
You can take a look at the core documentation to get a better feeling of why io_service is needed and what it does.
|
717,509
| 717,526
|
Is it ok to mutate objects with std::for_each?
|
for_each accepts InputIterators :
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
is it ok to change the object in Function f, like this :
struct AddOne
{
void operator()(int & x){x = x + 1;}
};
std::vector<int> vec(10);
std::for_each(vec.begin(),vec.end(),AddOne());
This code works in VC++2008 and also with GCC, but is it also portable (legal) code ?
(InputIterators are only guaranteed to be usable as rvalue, in this case they are used as lvalue in AddOne's operator())
|
Read this article.
To be pedantic: for_each is a non-modifying sequence operation. The intent is not to modify the sequence. However, it is okay to modify the input sequence when using for_each.
|
717,618
| 717,758
|
Simple server/client boost example not working
|
Learning boost, and compiled their daytime server client example. Since I cant use port 13 that is in the example I only changed the port numbers in the server and client example. Server runs fine, but the client doesnt connect it seems, and no error is given.
Input data for the client is "127.0.0.1".
Server:
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
int main()
{
try
{
boost::asio::io_service io_service;
tcp::endpoint endpoint(tcp::v4(), 8087);
tcp::acceptor acceptor(io_service, endpoint);
for (;;)
{
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
stream << "test" << make_daytime_string();
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
And the client:
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: daytime_client <host>" << std::endl;
return 1;
}
tcp::iostream s(argv[1], 8087);
std::string line;
std::getline(s, line);
std::cout << line << std::endl;
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << std::endl;
}
return 0;
}
|
A few things would help to debug this for you:
What platform are you running
What compiler are your using, including version
What version of boost are you using
Also, one thing to check is whether the server is binding to 127.0.0.1 or the external interface. Try using the IP address of your external interface instead of 127.0.0.1. Check this in windows using ipconfig and in linux using ifconfig.
|
717,622
| 717,639
|
Static Lib Multiple Definition Link Error
|
So I'm trying to build a small 3D engine as an exercise on VC++ 8.0. I have a MathLib static lib and a Render static lib that is being linked by my TestBed exe. Right now Render has two classes: Color and DXManager3D. Color includes my Vector.h from MathLib just fine, no problems.
The second I try to include Vector.h in DXManager3D it blows up on me, saying the symbol is defined twice, and the second definition is ignored (warning from lib). I thought maybe including it twice was causing this so as a test I removed Vector.h from Color.h and left it in DXManager3D.h - same problem. I have triple checked to make sure I have everything wrapped in ifndef to protect from this, so I am left scratching my head.
DXManager3D.obj : warning LNK4006: "public: __thiscall Math::Vector::Vector(void)" (??0Vector@Math@@QAE@XZ) already defined in Render.obj; second definition ignored
What really confuses me is that when I build the Render.lib separate from TestBed, which should not be linking anything as it is a static lib, right? I still get the multiple symbol definition warnings. If I instantiate a DXManager3D in main my warnings become errors.
Render.lib(DXManager3D.obj) : error LNK2005: "public: __thiscall Math::Vector::Vector(void)" (??0Vector@Math@@QAE@XZ) already defined in WinMain.obj
Yes, I have F1'd LNK4006 and LNK2005 and the solutions in the MSDN aren't working for me.
Sorry if this question has been asked before, I couldn't find anything solid to help me out using the search feature.
Thanks!
|
Is your Vector ctor defined in the header outside the class definition? Make it inline then i.e. change
class Vector {
public:
Vector();
// ...
};
Vector::Vector() {
// ...
}
to
class Vector {
public:
Vector() {}
// ...
};
or use an explicit inline qualification:
class Vector {
public:
Vector();
// ...
};
inline Vector::Vector() {
// ...
}
|
717,636
| 717,750
|
Is there an OS independent way to poll TOTAL and/or USED video memory?
|
I'm looking for a way to poll for total video memory on board a graphics cars / integrated chipset.
I'm aware of WMI assisted polling under Windows, and as far as I understand that information is constructed on every boot by WMI. However, being an optimist, I am looking for a possible OS independent way to poll for total video memory and free or used video memory.
If not possible, what would be the most elegant way to poll for same under Windows, Linux and OSX?
FYI I don't use DirectX under windows, only OpenGL.
|
There's no simple cross-platform way to do it. You'll have to either code up a way to do it yourself for each platform, or use a third-party library such as SDL to do it for you. For example, with SDL, you can use video_mem member of the return value from SDL_GetVideoInfo() to get the total video memory available.
|
717,729
| 717,741
|
Does extern "C" have any effect in C?
|
I just got some C code that uses extern "C" to declare external functions like this:
extern "C" void func();
Is this valid C? I'm getting an error at this line, but I'm not sure if it's because of this or something else.
|
No, it's not valid C. It should only be used in C++ code to refer to functions defined in C code. The extern "C" should be surrounded in a ifdef __cplusplus/#endif block:
// For one function
#ifdef __cplusplus
extern "C"
#endif
void func();
// For more than one function
#ifdef __cplusplus
extern "C"
{
#endif
void func1();
void func2();
#ifdef __cplusplus
}
#endif
|
717,759
| 717,764
|
Linker error when compiling vshadow, part of the Volume Shadow Copy Service SDK
|
I am getting this linker error when trying to compile the c++ project for the VSS SDK
Error 1 error LNK2019: unresolved external symbol "long __stdcall ShouldBlockRevert(wchar_t const *,bool *)" (?ShouldBlockRevert@@YGJPB_WPA_N@Z) referenced in function "public: void __thiscall VssClient::RevertToSnapshot(struct _GUID)" (?RevertToSnapshot@VssClient@@QAEXU_GUID@@@Z) revert.obj vshadow
The ShouldBlockRevert is used twice, once when it is declared at the top, and once when it is actually used.
Declared here:
HRESULT APIENTRY ShouldBlockRevert(IN LPCWSTR wszVolumeName, OUT bool* pbBlock);
and used here:
CHECK_COM(::ShouldBlockRevert(Snap.m_pwszOriginalVolumeName, &bBlock));
if (bBlock)
{
ft.WriteLine(L"Revert is disabled on the volume %s because of writers",
Snap.m_pwszOriginalVolumeName);
return;
}
Sorry, I'm not that good with c++.
|
According to this blog post:
As it happens, I ran dumpbin /exports on vssapi.lib, and found that it does export ShouldBlockRevert, but thanks to C++ name mangling the mangled name is different. Why is it different? Because in vssapi.lib, the first argument to ShouldBlockRevert isn’t wchar_t, it’s unsigned short. “So what”, you’re thinking, “they’re equivalent”. And I don’t disagree, but the compiler treats them as different types for name manging purposes. What’s the fix? Well, disable the intrinsic wchar_t type in the C/C++ Language property page in the project properties (equivalent to the /Zc:wchar_t- switch if you’re one of the two people on the planet who build Visual C++ projects with makefiles).
Once that’s done, the LPCWSTR macro is defined to unsigned short, name mangling matches, planets align, and you can link. QED.
|
718,029
| 718,034
|
Switch statement use
|
Should i use this form of switch statement:
switch(msg)
{
case WM_LBUTTONDOWN:
{
char szFileName[MAX_PATH];
HINSTANCE hInstance = GetModuleHandle(NULL);
GetModuleFileName(hInstance, (LPWCH)szFileName, MAX_PATH);
MessageBox(hwnd, (LPCWSTR)szFileName, L"This program is:", MB_OK | MB_ICONINFORMATION);
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
or make a function for the first case constant ?
|
There's nothing wrong with how you have it, but it's probably cleaner code to call a function so you can keep your functions a reasonable size.
|
718,447
| 789,025
|
Adding external library into Qt Creator project
|
How can I add external library into a project built by Qt Creator RC1 (version 0.9.2)? For example, the win32 function EnumProcesses() requires Psapi.lib to be added in the project to build.
|
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_ variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
|
718,451
| 718,471
|
should I use the algorithm or hand-code it in this case?
|
Ok, someone tell me which would be better. I need to |= the elements of one vector with another. That is, I want to
void orTogether(vector<char>& v1, const vector<char>& v2)
{
typedef vector<char>::iterator iter;
for (iter i = v1.begin(), iter j = v2.begin() ; i != v1.end(); ++i, ++j)
*i |= *j;
}
I can't use for_each due to needing to process 2 collections. I suppose I could do something like
struct BitWiseOr
{
char operator()(const char& a, const char& b) {return a | b;}
};
void orTogether2(vector<char>& v1, const vector<char>& v2)
{
transform(v1.begin(), v1.end(), v2.begin(),
v1.begin(), BitwiseOr());
}
Is this a more efficient solution even though the top one is in place, but the bottom is an assign? This is right in the middle of a processing loop and I need the fastest code possible.
Edit: Added (obvious?) code for BitwiseOr. Also, I'm getting a lot of comments on non-related things like checking the lengths of v2 and changing the names. This is just an example, the real code is more complicated.
Well, I profiled both. orTogether2 is much faster than orTogether, so I'll be going with the transform method. I was surprised, orTogether2 was about 4 times faster in MSVC9 release mode. I ran it twice, changing the order the second time to make sure it wasn't some sort of cache issue, but same results. Thanks for the help everyone.
|
The bottom one will compile to effectively the same as the first, your OR functor is going to be inlined for sure. So the second idiom is more flexible if you ever need to add more flexibility or debugging frameworks or whatever.
Since there's no benefit to the first, use the transform method. Once you get into that habit you'll stop even considering the explicit loop choice for all your apps since it's unnecessary. The only advantage to the first method is it's easier to explain to beginner C++ programmers who are more comfortable with raw C.
|
718,490
| 718,507
|
Segmentation fault in strcpy
|
consider the program below
char str[5];
strcpy(str,"Hello12345678");
printf("%s",str);
When run this program gives segmentation fault.
But when strcpy is replaced with following, program runs fine.
strcpy(str,"Hello1234567");
So question is it should crash when trying to copy to str any other string of more than 5 chars length.
So why it is not crashing for "Hello1234567" and only crashing for "Hello12345678" ie of string with length 13 or more than 13.
This program was run on 32 bit machine .
|
There are three types of standards behaviour you should be interested in.
1/ Defined behaviour. This will work on all complying implementations. Use this freely.
2/ Implementation-defined behaviour. As stated, it depends on the implementation but at least it's still defined. Implementations are required to document what they do in these cases. Use this if you don't care about portability.
3/ Undefined behaviour. Anything can happen. And we mean anything, up to and including your entire computer collapsing into a naked singularity and swallowing itself, you and a large proportion of your workmates. Never use this. Ever! Seriously! Don't make me come over there.
Copying more that 4 characters and a zero-byte to a char[5] is undefined behaviour.
Seriously, it doesn't matter why your program crashes with 14 characters but not 13, you're almost certainly overwriting some non-crashing information on the stack and your program will most likely produce incorrect results anyway. In fact, the crash is better since at least it stops you relying on the possibly bad effects.
Increase the size of the array to something more suitable (char[14] in this case with the available information) or use some other data structure that can cope.
Update:
Since you seem so concerned with finding out why an extra 7 characters doesn't cause problems but 8 characters does, let's envisage the possible stack layout on entering main(). I say "possible" since the actual layout depends on the calling convention that your compiler uses. Since the C start-up code calls main() with argc and argv, the stack at the start of main(), after allocating space for a char[5], could look like this:
+------------------------------------+
| C start-up code return address (4) |
| argc (4) |
| argv (4) |
| x = char[5] (5) |
+------------------------------------+
When you write the bytes Hello1234567\0 with:
strcpy (x, "Hello1234567");
to x, it overwrites the argc and argv but, on return from main(), that's okay. Specifically Hello populates x, 1234 populates argv and 567\0 populates argc. Provided you don't actually try to use argc and/or argv after that, you'll be okay:
+------------------------------------+ Overwrites with:
| C start-up code return address (4) |
| argc (4) | '567<NUL>'
| argv (4) | '1234'
| x = char[5] (5) | 'Hello'
+------------------------------------+
However, if you write Hello12345678\0 (note the extra "8") to x, it overwrites the argc and argv and also one byte of the return address so that, when main() attempts to return to the C start-up code, it goes off into fairy land instead:
+------------------------------------+ Overwrites with:
| C start-up code return address (4) | '<NUL>'
| argc (4) | '5678'
| argv (4) | '1234'
| x = char[5] (5) | 'Hello'
+------------------------------------+
Again, this depends entirely on the calling convention of your compiler. It's possible a different compiler would always pad out arrays to a multiple of 4 bytes and the code wouldn't fail there until you wrote another three characters. Even the same compiler may allocate variables on the stack frame differently to ensure alignment is satisfied.
That's what they mean by undefined: you don't know what's going to happen.
|
718,503
| 718,513
|
Stack corruption in C++
|
In C++, in which way the stack may get corrupted. One way I guess is to overwriting the stack variables by accessing an array beyond its boundaries. Is there any other way that it can get corrupted?
|
You could have a random/undefined pointer that ends up pointing to the stack, and write though that.
An assembly function could incorrectly setup/modify/restore the stack
Cosmic waves could flips bits in the stack.
Radioactive elements in the chip's casing could flip bits.
Anything in the kernel could go wrong and accidentally change your stack memory.
But those are not particular to C++, which doesn't have any idea of the stack.
|
718,676
| 718,745
|
Using Boost MPI for sending files?
|
Can I use the Boost MPI to send files to other computers? My worry is that it is optimized for very small messages and not larger (I need to send 700 MB or more in one go). The reason is that I will probably use mpi for other parts of the program anyway so I thought it would be a pretty clean solution to not mix and match.
Has it been done? Would you recommend it?
|
Keep in mind that Boost MPI requires that you already have an MPI implementation on the systems you want to send files with (OpenMPI, MPICH2, MVAPICH2, etc). You'll need to get one of these to go along with Boost MPI.
Also keep in mind that MPI is designed for high performance clusters, and most MPI implementations assume that you have reliable hardware. That is, if you've written an application in MPI and one of your processes goes down, more than likely they're all going to die.
If you're planning to use this in a local environment on your own network, and you intend to run mostly batch jobs and not persistent services, then MPI might be a good choice. If not, then look into some other messaging solution designed for a more distributed, less reliable environment.
|
718,866
| 718,875
|
Method to find "cleanest" subset of data i.e. subset with lowest variability
|
I am trying to find a trend in several datasets. The trends involve finding the best fit line, but if i imagine the procedure would not be too different for any other model (just possibly more time consuming).
There are 3 conceivable scenarios:
All good data where all the data fits a single trend with a low variability
All bad data where all or most of the data exhibits tremendous variability and the entire dataset must be discarded.
Partial good data where some of the data may be good while the rest needs to be discarded.
If the net percentage of data with extreme variability is too high then the entire set must be discarded. This implies that there is essentially only this type of data and the percentage of bad data varies:
0% bad = Case 1
100% bad = Case 2
I am only looking for contiguous sections with low variablity; i.e. I don't care if there are some individual points that fit the trend
What I am looking for is a smart way to subsection section the dataset and search for the specified trend. As is the nature of the problem, I am not looking for sections that best fit the overall trend. I understand that the subsection with "cleaner" data will end up having slightly different trendline properties than the overall (which would contain the outliers). This is exactly what i want since this part of the data would best best reflect the actual trend.
I am fluent in C++ but, since I am trying to make the code open source and cross-platform, I am stick to ISO C++ standards. This implies no .NET but if you have a .NET example I would appreciate if you could also help me convert it to ISO C++. I also have knowledge of JAVA, some assembly and fortran.
The datasets themselves are not huge but there are about 150 million of them and so brute force may not be the best way.
Thanks in advance
I understand that I have left some things up in the air and so let me clarify:
Each dataset can, and probably will, have different trends; i.e. I am not looking for the same trend throughout all datasets.
The program user will define how close a fit they want
The program user will define how contiguous the subset must be before it its considered for trend fitting
In case the program is extended to allow for any type of fit (not simply linear), the user will define what model is to be fit -- THIS IS NOT A PRIORITY and if the above query is solved then I am sure this expansion would be relatively trivial
The outliers come about as a result of the nature of the experiment and the data acquisition technique whereby data from "bad" sections must still be collected even though these areas are known to give outliers. The discarding of these outliers DOES NOT imply that the data is being manipulated to fit any trend (statistics disclaimer, hehe).
|
The RANSAC algorithm is one approach to what you're looking for if I understand you right. http://en.wikipedia.org/wiki/RANSAC
|
718,896
| 718,902
|
How is the sizeof operator implemented in c++?
|
Can someone point me the to the implementation of sizeof operator in C++ and also some description about its implementation.
sizeof is one of the operator that cannot be overloaded.
So it means we cannot change its default behavior?
|
sizeof is not a real operator in C++. It is merely special syntax which inserts a constant equal to the size of the argument. sizeof doesn't need or have any runtime support.
Edit: do you want to know how to determine the size of a class/structure looking at its definition? The rules for this are part of the ABI, and compilers merely implement them. Basically the rules consist of
size and alignment definitions for primitive types;
structure, size and alignment of the various pointers;
rules for packing fields in structures;
rules about virtual table-related stuff (more esoteric).
However, ABIs are platform- and often vendor-specific, i.e. on x86 and (say) IA64 the size of A below will be different because IA64 does not permit unaligned data access.
struct A
{
char i ;
int j ;
} ;
assert (sizeof (A) == 5) ; // x86, MSVC #pragma pack(1)
assert (sizeof (A) == 8) ; // x86, MSVC default
assert (sizeof (A) == 16) ; // IA64
|
718,972
| 719,007
|
Storing a COM pointer in a struct
|
My program is crashing every time I try to store a COM pointer into a struct, and then later try to use the original pointer. I don't have debug access to tell exactly what's wrong.
pRend->cp = cpRT;
ID2D1SolidColorBrush *scBrush;
ERF(cpRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::CornflowerBlue), &scBrush));
It crashes on CreateSolidColorBrush. However, if I comment out pRend->cp = cpRT, it doesn't.
By the way, pRend->cp and cpRT are of type ID2D1HwndRenderTarget *.
|
As it turns out, I managed to stop the crashing by allocating pRend with malloc. This is not a problem because I will call free when I don't need it anymore. I'm interested in why calling malloc fixes this though. I'm used to just doing Datatype * var; and then just using var. Is that bad?
|
719,043
| 719,491
|
Call member function on each element in a container
|
This question is a matter of style, since you can always write a for loop or something similar; however, is there a less obtrusive STL or BOOST equivalent to writing:
for (container<type>::iterator iter = cointainer.begin();
iter != cointainer.end();
iter++)
iter->func();
?
Something like (imagined) this:
call_for_each(container.begin(), container.end(), &Type::func);
I think it would be 1) less typing, 2) easier to read, 3) less changes if you decided to change base type/container type.
EDIT:
Thanks for your help, now, what if I wanted to pass some arguments to the member function?
|
I found out that boost bind seems to be well suited for the task, plus you can pass additional arguments to the method:
#include <iostream>
#include <functional>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
struct Foo {
Foo(int value) : value_(value) {
}
void func(int value) {
std::cout << "member = " << value_ << " argument = " << value << std::endl;
}
private:
int value_;
};
int main() {
std::vector<Foo> foo_vector;
for (int i = 0; i < 5; i++)
foo_vector.push_back(Foo(i));
std::for_each(foo_vector.begin(), foo_vector.end(),
boost::bind(&Foo::func, _1, 1));
}
|
719,124
| 719,316
|
Knowing C++, how long does it take to learn Java?
|
I am a competent C++ developer. I understand and use polymorphism, templates, the STL, and I have a solid grasp of how streams work. For all practical purposes, I've done no Java development. I'm sure some of you were in a similar situation at one point when you had to learn Java. How long did it take you to become a competent Java programmer?
|
I think that learning the language is not difficult. In fact, I used to be a full time C++ developer, and at some point I started writing Java code. But the thing is that I don't remember ever learning Java, so I guess I just figured it as I went. I've been doing full time Java for a long time now.
If you are well familiar with C++, you may want to read a list of the major differences (e.g., everything is dynamically-bound) and then start practicing on an environment (just download Eclipse). The small differences are the main thing you would have to get adjusted to.
Now that Java supports generics, one of the major switching pains is gone. Multiple inheritance, while not supported, is not a big deal if you get used to interfaces, and in fact having interfaces rather than abstract classes with pure virtual functions (PVFs) improves readability.
To me Java is a nice and friendly and relaxing sandboxed version of C++. I don't have to worry about general protection faults (GPFs), I don't have to worry about memory leaks, I don't have to worry about messing with pointers. However, don't let that confuse you, there are still plenty of opportunities to screw up royally, and they're sometimes even nastier to detect.
Just take the leap. If you have the instinct, it shouldn't be a problem.
|
719,364
| 719,499
|
Which GUI framework is used by the "Spybot Search & Destroy" application?
|
I want to replicate the look and feel of Spybot Search & Destroy in my own applications. Is there a publicly-available framework, toolkit, or library to aid in this task?
|
AFAICR it's written in Delphi. With C++ Builder you can use Delphi libraries from C++.
|
719,645
| 719,676
|
How does 2 or more processes interact with the keyboard?
|
I have been thinking a lot over keyboard handling. How does it work? I can't seem to google me to a good explaining.
I know that a keyboard interrupt is made every time a key is pressed. The processor halts whatever it is processing and load the keyboard data from the keyboard buffer, storing it in a system level buffer.
But what happens next? Let's take a practical example. What happens when I run the following piece of code:
...
std::string s;
std::cin >> s;
....
Does the cin read from a user level representation of the system level keyboard buffer? That makes perfect sense in my head because then 2, or more processes can read from the same buffer, and by that way I don't loose any key presses. But does it work this way?
I know I'm talking in very general terms. The OS I'm using is OS X.
|
Except in rare situations, your keyboard and display are managed by a Window Manager: X11, Gnome, KDE, Carbon, Cocoa or Windows.
It works like this.
The keyboard driver is part of the OS.
The window manager is a privileged process, which acquires the device during startup. The window manager "owns" the device. Exclusively.
The interrupts go to OS.
The OS responds the interrupt by queueing. Eventually -- when there's nothing of a higher priority to do -- it captures the keyboard input from the interrupt and buffers it.
The owning process (the window manager) is reading this buffer. From this, it creates keyboard events.
Your application works through the window manager.
Example 1 -- You're running a command-line application. In a terminal window. When terminal window is front-most, the window manager directs events at the terminal window. Keyboard events become the stdin stream.
Example 2 -- you're running GUI application. In your own application's window. When your application's window is front-most, the window manager direct events at your application window. Keyboard events are available for your various GUI controls to process. Some keyboard events may cycle among the controls or active buttons.
|
719,650
| 719,709
|
open source dev environment for C++: what's better?
|
I want to do some coding in my spare time, but the thing is, I don't want to spend the money on this.
Would the following set of development tools be The Right Thing, or is there something I'm forgetting?
Eclipse for C++
SVN for source control
Qt for UI development (since it's C++, and I believe it's now opened by Nokia)
hudson for continuous integration
I'd like to write a little image processing application that can run on any platform, but the main platform at the moment will be Windows with a possible movement to the Mac-- hence all the cross-platform tools.
Is there anything really obvious I'm forgetting? Like something like fxcop for style checking in C++?
If I use any libraries, I'd like to avoid GPL libraries; if things go south with my current employer, I'll want to monetize this.
|
Microsoft Visual C++ Express is free and easily the best IDE for Windows. Furthermore, you can use it to work on cross-platform code - it more depends on writing standards-adhering code and using portable libraries.
If you want to write cross-platform code, I recommend a cross-platform build tool. I use CMake, which generates Visual Studio solutions on Windows, but there are others too, such as SCons.
As for libraries, it depends on what exactly you need to do. Qt is an excellent GUI library. libpng/libjpeg and others are good for loading/saving images at a low level, but there are probably other higher-level image libraries as well.
[edit] A response to the comment about MSVC and Qt:
A quick search brings up Trolltech's Qt Visual Studio Integration page:
Qt Visual Studio .NET Integration
A comment points out that this is actually not free (a free addon is available at this link, but this runs Qt designer outside of Visual Studio. Also, the Express version of Visual Studio does not support plugins.
For coding specifically in Qt there is another new IDE created by Qt: Qt Creator. I've heard good things about it, and it is also portable across Windows, Linux, and Mac.
|
720,004
| 720,016
|
How do I call unmanaged C/C++ code from a C# ASP.NET webpage
|
I have an ASP.NET website that uses C# and I'd like to call functions from an unmanaged C/C++ DLL. How do I do it?
|
Check out P/Invoke.
Calling Win32 DLLs in C# with P/Invoke
If it's a COM dll, then you can use COM Interop
|
720,049
| 720,059
|
Initialization and Assignment
|
I have some 'legacy' code (which I can't change, but need to add on to) that looks something like this:
template<typename T> T Foo(T& target)
{
//Assign to 'target', but never read from it before that.
//Also, 'target' is going to be a POD-type.
target = T();
return target;
}
int main()
{
float value = Foo(value);
}
This feels unsafe (i.e., making sure that target is never assigned to before it's used), are there any other potentially lethal problems with this sort of interface?
|
Well.. If you do the code:
T value;
then value will get it's constructor called on it. The template honestly just looks like the constructor is just getting called twice.
Also, if T is just plain old data, then there is no lethal problem that could occur...
What exactly are you worried about occurring?
|
720,344
| 720,352
|
Concatenating strings
|
I want to join a vector<string> into a single string, separated by spaces. For example,
sample
string
for
this
example
should become "sample string for this example".
What is the simplest way to do this?
|
#include <iterator>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::vector<std::string> v;
...
std::stringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(ss, " "));
std::string result = ss.str();
if (!result.empty()) {
result.resize(result.length() - 1); // trim trailing space
}
std::cout << result << std::endl;
|
720,440
| 720,450
|
Visual C++ error C2143: syntax error: missing ')' before 'constant'
|
I'm getting an error in Visual C++ that is giving me a really hard time.
The error is error c2143 reading: syntax error: missing ')' before 'constant'
My code line is:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
I have #include at the beginning of the file which should define the floor(double) function.
a bit more explanation of the variables.
double depth is a member variable of the class which this line can be found in.
int i is an incrementing index value.
double t is an incrementing value.
What they do is really unimportant, but I wanted to clarify that all three are already defined as variables of basic types.
I've gone through and verified that all the parentheses match up. I'm kind of at a loss as to what 'constant' the compiler is referring to. Any ideas?
|
I'm not quite sure if this is the same error that the compiler is giving you, but you have to put a '*' sign in front of the second '2' so that this:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) 2 * depth);
Becomes this:
coefficient[i] = (1 - (2 * depth)) + ((t - floor( t + 0.5 ) + 1 ) * 2 * depth);
|
720,507
| 720,520
|
How can i estimate memory usage of std::map?
|
For example, I have a std::map with known sizeof(A) and sizeof(B), while map has N entries inside. How would you estimate its memory usage?
I'd say it's something like
(sizeof(A) + sizeof(B)) * N * factor
But what is the factor? Different formula maybe?
Maybe it's easier to ask for upper bound?
|
The estimate would be closer to
(sizeof(A) + sizeof(B) + ELEMENT_OVERHEAD) * N + CONTAINER_OVERHEAD
There is an overhead for each element you add, and there is also a fixed overhead for maintaining the data structure used for the data structure storing the map. This is typically a binary tree, such as a Red-Black Tree. For instance, in the GCC C++ STL implementation ELEMENT_OVERHEAD would be sizeof(_Rb_tree_node_base) and CONTAINER_OVERHEAD would be sizeof(_Rb_tree). To the above figure you should also add the overhead of memory management structures used for storing the map's elements.
It's probably easier to arrive at an estimate by measuring your code's memory consumption for various large collections.
|
720,707
| 720,738
|
how to return two dimensional char array c++?
|
i ve created two dimensional array inside a function, i want to return that array, and pass it somewhere to other function..
char *createBoard( ){
char board[16][10];
int j =0;int i = 0;
for(i=0; i<16;i++){
for( j=0;j<10;j++){
board[i][j]=(char)201;
}
}
return board;
}
but this keeps giving me error
|
Yeah see what you are doing there is returning a pointer to a object (the array called board) which was created on the stack. The array is destroyed when it goes out of scope so the pointer is no longer pointing to any valid object (a dangling pointer).
You need to make sure that the array is allocated on the heap instead, using new. The sanctified method to create a dynamically allocated array in modern C++ is to use something like the std::vector class, although that's more complicated here since you are trying to create a 2D array.
char **createBoard()
{
char **board=new char*[16];
for (int i=0; i<16; i++)
{
board[i] = new char[10];
for (int j=0; j<10; j++)
board[i][j]=(char)201;
}
return board;
}
void freeBoard(char **board)
{
for (int i=0; i<16; i++)
delete [] board[i];
delete [] board;
}
|
720,744
| 720,783
|
Class with static members vs singleton
|
Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help.
|
This kind of class is known as a monostate - it is somewhat different from a singleton.
Why use a monostate rather than a singleton? In their original paper on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):
More natural access syntax
singleton lacks a name
easier to inherit from
I must admit, I don't find any of these particularly compelling. On the other hand, the monostate is definitely no worse than the singleton.
|
720,817
| 723,240
|
Boost, sending files over the network using tcp, prefered method?
|
In the boost examples in the documentation, tcp:iostream is used to very simply send streams over the network. In other examples write() is used to write data to the socket instead with a bit more code involved.
What is the difference between those 2 methods? Pros and cons? Is there something else that should be used instead ?
|
I've never used the boost API, so reader beware... ;)
The tcp::iostream appears to allow you to interact with the socket with a stream-like interface. This approach abstracts the complexities associated with socket programming, so it would be preferable especially if you are new to socket programming. It makes a lot of sense for TCP-based data sharing. It is especially convenient if you are doing very simple data exchanges, such as request/response.
However, there are cases where you need lower-level control over the data exchange. If your receiver receives a bunch of messages at the same time, you may prefer to read each message from the socket instead of processing them after the fact from the iostream. On the sender side, if your messages are structured as objects, it is often easier just to send the object instead of first converting the object to a stream. The read/write functionality would be preferable in this case.
From my own (non-boost) socket programming experience, I usually prefer dealing with the lower-level functions since it gives me more flexibility even though it is slightly more complex. I hope that helps.
|
720,838
| 720,855
|
CXX Test Framework for C++
|
How effective is the CXX test framework, given that you are writing unit test cases around the code that you have written. Any bug in the code might as well get translated into a bug in the unit test code as well? Isn't it something like two negatives make a positive?
Also, the time and effort spent on CXX is at least equal to if not more than the coding effort.
Need your thoughts on this since I'm not in favor of this framework being used in my project and am looking for strong points to oppose it.
On the other hand, if you think it's beneficial, please do enlighten me :).
|
CXX is not very active, and writing unit test generally involves a lot of efforts. But when the first refactoring comes in, you're very grateful of the spent effort.
I've used Boost.Test & CPPUNIT. I would prefer a little bit Boost.Test, but yes, you have to write your own projects, files etc.
If you know a tool to generate your skeleton from your code, I'm all ears. :)
I would suggest that you give a try to Boost.Test and CPPUNIT. If you think there are better it will give you good rounds to oppose CXXUNIT as you will propose alternatives.
|
721,129
| 721,137
|
Spot the error in this file reading code (C++)
|
Can anyone please tell my why this method won't compile?
void Statistics::readFromFile(string filename)
{
string line;
ifstream myfile (filename);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
}
Should work, right? Yet, I always get the following error message:
Line Location Statistics.cpp:15: error:
no matching function for call to
'std::basic_ifstream<char, std::char_traits<char> >::
basic_ifstream(std::string*)'
any help would be greatly appreciated.
|
ifstream myfile (filename);
should be:
ifstream myfile (filename.c_str() );
Also, your read-loop logic is wrong. It should be:
while ( getline( myfile,line ) ){
cout << line << endl;
}
The eof() function that you are using is only meaningful after you have tried to read read something.
To see why this makes a difference, consider the simple code:
int main() {
string s;
while( ! cin.eof() ) {
getline( cin, s );
cout << "line is "<< s << endl;
}
}
If you run this and type ctrl-Z or ctrl-D to indicate EOF immediately, the cout will be performed even though no line has actually been input (because of the EOF). In general, the eof() function is not very useful, and you should instead test the return value of functions like getline() or the stream extraction operators.
|
721,357
| 721,362
|
Unexpected output of std::wcout << L"élève"; in Windows Shell
|
While testing some functions to convert strings between wchar_t and utf8 I met the following weird result with Visual C++ express 2008
std::wcout << L"élève" << std::endl;
prints out "ÚlÞve:" which is obviously not what is expected.
This is obviously a bug. How can that be ? How am I suppose to deal with such "feature" ?
|
The C++ compiler does not support Unicode in code files. You have to replace those characters with their escaped versions instead.
Try this:
std::wcout << L"\x00E9l\x00E8ve" << std::endl;
Also, your console must support Unicode as well.
UPDATE:
It's not going to produce the desired output in your console, because the console does not support Unicode.
|
721,548
| 721,665
|
cross platform game development what to look for?
|
I am going to start a game in about 3 weeks and I would really like the game to run at least on another platform (linux, MacOS) but my team thinks that's a lot of work. I am up for it but wanted to know what are the things I should watch out for that won't port to linux (apart from Windows specific APIs like DirectXsound)?
I've been reading online and Windows "_s" functions like sprintf_s appear to exist only on Windows; is this correct or are they implemented on linux also?
|
No, the _s functions are NOT implemented in the standard gcc library.
(At least, grepping the include files for 'sprintf_s' turns up nothing at all.)
It might be worth looking at cross platform libraries like boost and apr to do some of the heavy lifting work.
A sample of specific things to look for:
Input/Output (DirectX / SDL / OpenGL)
Win32/windows.h functionality (CreateThread, etc)
Using windows controls on the UI
Synchronization primitives (critical sections, events)
Filepaths (directory separators, root names)
Wide char implementations (16 bit on windows, 32bit on linux)
No MFC support on linux (CString, etc)
|
721,705
| 721,901
|
How do I set the opacity of a vertex in OpenGL?
|
The following snippet draws a gray square.
glColor3b(50, 50, 50);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
In my application, behind this single square exists a colored cube.
What function should I use to make square (and only this square) opaque?
|
In the init function, use these two lines:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
And in your render function, ensure that glColor4f is used instead of glColor3f, and set the 4th argument to the level of opacity required.
glColor4f(1.0, 1.0, 1.0, 0.5);
glBegin(GL_QUADS);
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
|
721,802
| 721,856
|
What disadvantages could I have using OpenGL for GUI design in a desktop application?
|
There are tons of GUI libraries for C/C++, but very few of them are based on the idea that opengl is a rather multiplatform graphics library. Is there any big disadvantage on using this OpenGL for building my own minimal GUI in a portable application?
Blender is doing that, and it seems that it works well for it.
EDIT: The point of my question is not about using an external library or making my own. My main concern is about the use of libraries that use opengl as backend. Agar, CEGUI or Blender's GUI for instance.
Thanks.
|
Here's an oddball one that bit a large physics experiment I worked on: because an OpenGL GUI bypasses some of the usual graphics abstraction layers, it may defeat remote viewing applications.
In the particular instance I'm thinking of we wanted to allow remote shift operations over VNC. Everything worked fine except for the one program (which we only needed about once per hour, but we really needed) that used an OpenGL interface. We had to delay until a remote version of the OpenGL interface could be prepared.
|
721,810
| 721,863
|
What's an OCCI context and environment?
|
I'm exploring a piece of software making use of Oracle API and as far as I can see often object methods expect as an argument a "OCCI context" or a "OCCI environment" values.
An example is a constructor of an Account object:
Account( oracle::occi::Environment* env );
later overloaded with
Account( void* oraCtx );
I can understand that somehow they have to do with sort of a "connection handler", but I'd like to know more.
I googled around but I couldn't find anything clear enough for me, it seems every doc starts from the assumption you already know Oracle API.
Thanks.
|
OCCI Environment lets you define your own memory management functions which OCCI will later use.
When you create an environment, you pass the pointers to your own malloc, realloc and free:
static Environment * createEnvironment(Mode mode = DEFAULT,
void *ctxp = 0,
void *(*malocfp)(void *ctxp, size_t size) = 0,
void *(*ralocfp)(void *ctxp, void *memptr, size_t newsize) = 0,
void (*mfreefp)(void *ctxp, void *memptr) = 0);
Context is just a pointer to an Environment that is passed to these functions when OCCI calls them.
|
721,855
| 721,891
|
accumulate the sum of elements in map, using value
|
Say I have a
struct SMyStruct
{
int MULT;
int VAL;
};
std::map<std::string, SMyStuct*> _idToMyStructMap;
Now I want to calculate total of all SMyStuct, where total is defined as MULT1 *VAL1 + MULT2 *VAL2 for each elements in the idToMyStructMap.
Seems like accumulate function is a natural choice. Please suggest. thanks
No Boost please.... just an 'ld fashion stl
|
typedef std::map< std::string, SMyStruct* > string_to_struct_t;
int add_to_totals( int total, const string_to_struct_t::value_type& data )
{
return total + data.second->MULT * data.second->VAL;
}
const int total = std::accumulate(
_idToMyStructMap.begin(),
_idToMyStructMap.end(),
0,
add_to_totals );
|
721,861
| 721,996
|
In case of integer overflows what is the result of (unsigned int) * (int) ? unsigned or int?
|
In case of integer overflows what is the result of (unsigned int) * (int) ? unsigned or int? What type does the array index operator (operator[]) take for char*: int, unsigned int or something else?
I was auditing the following function, and suddenly this question arose. The function has a vulnerability at line 17.
// Create a character array and initialize it with init[]
// repeatedly. The size of this character array is specified by
// w*h.
char *function4(unsigned int w, unsigned int h, char *init)
{
char *buf;
int i;
if (w*h > 4096)
return (NULL);
buf = (char *)malloc(4096+1);
if (!buf)
return (NULL);
for (i=0; i<h; i++)
memcpy(&buf[i*w], init, w); // line 17
buf[4096] = '\0';
return buf;
}
Consider both w and h are very large unsigned integers. The multiplication at line 9 have a chance to pass the validation.
Now the problem is at line 17. Multiply int i with unsigned int w: if the result is int, it is possible that the product is negative, resulting in accessing a position that is before buf. If the result is unsigned int, the product will always be positive, resulting in accessing a position that is after buf.
It's hard to write code to justify this: int is too large. Does anyone has ideas on this?
Is there any documentation that specifies the type of the product? I have searched for it, but so far haven't found anything.
I suppose that as far as the vulnerability is concerned, whether (unsigned int) * (int) produces unsigned int or int doesn't matter, because in the compiled object file, they are just bytes. The following code works the same no matter the type of the product:
unsigned int x = 10;
int y = -10;
printf("%d\n", x * y); // print x * y in signed integer
printf("%u\n", x * y); // print x * y in unsigned integer
Therefore, it does not matter what type the multiplication returns. It matters that whether the consumer function takes int or unsigned.
The question here is not how bad the function is, or how to improve the function to make it better. The function undoubtedly has a vulnerability. The question is about the exact behavior of the function, based on the prescribed behavior from the standards.
|
To answer your question: the type of an expression multiplying an int and an unsigned int will be an unsigned int in C/C++.
To answer your implied question, one decent way to deal with possible overflow in integer arithmetic is to use the "IntSafe" set of routines from Microsoft:
http://blogs.msdn.com/michael_howard/archive/2006/02/02/523392.aspx
It's available in the SDK and contains inline implementations so you can study what they're doing if you're on another platform.
|
721,998
| 987,892
|
Why does my colored cube not work with GL_BLEND?
|
My cube isn't rendering as expected when I use GL_BLEND.
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
I'm also having a similar problem with drawing some semi-opaque vertices in front, which could well be related.
Related: Why do my semi-opaque vertices make background objects brighter in OpenGL?
Here's what it's supposed to look like:
Normal cube http://img408.imageshack.us/img408/2853/normalcube.png
And here's what it actually looks like:
Dark cube http://img7.imageshack.us/img7/7133/darkcube.png
Please see the code used to create the colored cube, and the code used to actually draw the cube.
The cube is being drawn like so:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glLoadIdentity();
// ... do some translation, rotation, etc ...
drawCube();
glPopMatrix();
// ... swap the buffers ...
|
You could try disabling all lighting before drawing the cube:
glDisable(GL_LIGHTING);
|
722,257
| 722,309
|
should I take arguments to inline functions by reference or value?
|
Is one of these faster?
inline int ProcessByValue(int i)
{
// process i somehow
}
inline int ProcessByReference(const int& i)
{
// process i somehow
}
I know that integral types should be passed by value. However, I am concerned that the compiler might inline ProcessByValue to contain a copy. Is there a rule for this?
|
The parameter should be typed according to what makes sense for the function.
If the function takes a primitive type, pass by value would make sense. Some people I know would complain if it were passed by const ref (as it's 'unnecessary'), but I don't think I'd complain. If the function takes a user defined type and doesn't modify the parameter, then pass by const ref would make sense.
If it's a user defined type and the parameter is modified, then the semantics of the function would dictate how it should be passed.
|
722,268
| 722,289
|
Using map containing set as a value
|
Basically I have,
typedef map<std::string, set<double> > MAP_STRING_TO_SET;
What is the best way to update (add or remove value) the set with a new value without causing the set to be copied?
The only viable solution I see is to use map<std::string, set<double>* > -- something I don't want to do.
Thanks
|
The set is only copied in initialization.
You are allowed to do something like
myMap[myString].insert(myDouble);
since map::operator[] returns a reference.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.