question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,458,162 | 2,458,215 | How to get this to compile? | I have this code which compiles and works as expected:
class Right
{};
class Left
{
public:
Left& operator = (Right const&)
{
//... Do something ...
return *this;
}
};
int main()
{
Right right;
Left left;
// Assign individual object -- this works
left = right;
}
But now, this one surprises me, I thought the template would work itself out since I already provided the = operator() to the Left class.
int main()
{
...
std::list<Right> rightLst;
std::list<Left> leftLst;
// Assign a list of objects -- this doesn't compile
leftLst = rightLst;
}
What can I do so that I could convert the rightLst to leftLst conversion in a single line?
Also, what if explicit keyword is used on Left? Then none of the proposed solutions will work, i.e. if Left is defined as:
class Left
{
public:
Left()
{}
explicit Left(Right const& right_)
{
.. // Do something ..
}
Left& operator = (Right const& right_)
{
// .. Do something ..
return *this;
}
};
See, I'm trying to avoid writing this code below to achieve what I want to do:
for(std::list<Right>::iterator it = rightLst.begin();
it != rightLst.end();
it++ )
{
leftLst.push_back(Left(*it));
}
What code from STL I could re-use to replace the above?
| Use:
std::copy(rightLst.begin(), rightLst.end(), std::back_inserter(leftLst));
This will add new elements to the end of leftLst corresponding to the elements in rightLst. You will need to add a constructor to Left that takes const Right &.
If leftLst and rightLst already contain the same number of elements and you want to overwrite the elements in leftLst, use:
std::copy(rightLst.begin(), rightLst.end(), leftLst.begin());
Edit:
Even simpler is to use:
leftLst.assign(rightLst.begin(), rightLst.end());
This will replace all elements (if any) in leftLst, so it will cover both cases given above.
The reason that the normal assignment operator doesn't work here is that the standard defines it to only accept a list of the same type, so it won't allow assigning from list<Right> to list<Left>.
If the constructor is declared explicit, there won't be a way for the assign function to know how to convert Right to Left, so it won't work. Another option is to define a conversion operator on Right instead:
Right::operator Left() { return Left();}
If you do neither, assign will fail to compile.
The second version of copy given above will work without a conversion operator or a conversion constructor (only an assignment operator is needed), but it requires the target list to have enough elements.
|
2,458,232 | 2,458,587 | Adjust parameters of serial port reading | I'm facing a particular issue that regards serial communication under win32.
I'm communicating with a device can only accept frames when it is not already communicating. So I must find a valid frame and then inmediatelly send my request.
I developed a class named Serial that handles basic operations on serial port (open, close, read, write) and then a Thread calls inside a loop read and write functions.
Thread loop
//Device is an object of class Serial
while( device->isOpen() && !terminate )
{
unsigned int readed = 0;
unsigned long error = ERROR_SUCCESS;
unsigned char* data = device->read( &readed, &error );
if( error==ERROR_SUCCESS )
{
//If data received, deliver to upper level
if( readed>0 )
{
QByteArray output( (const char*)data, (signed int)readed );
emit dataArrived( output, readed );
}
}
else
{
//unrelated stuff
}
//Here I manage the writting issue
//Only when nothing is received, and Upper layer wants to send a frame
//(Upper layer only will mark as something to send when it detects a valid frame)
if( readed==0 )
{
out_lock.lock();
//If something to send...
if( something_to_send > 0 )
{
if( device->write( output_buffer, output_size, &error ) )
{ //things...
}
}
}
}
The Thread basically keeps reading, and when nothing is received, sees if somebody has signaled to send a frame (this means that a valid frame is just received).
When this happens, it writes the frame through serial port.
Here comes my problem.
Inside the Serial::read() function:
I use the overlapped way of reading:
::ClearCommError( handle, &dwErrors, &stat);
if( stat.cbInQue )
{
//If there's something to read, read it, please note the bytes to read parameter, here 1.
bool ok = ::ReadFile( handle, buffer_in, 1, &bytes_read, &ov_reader );
if( !ok )
{
DWORD _error = ::GetLastError();
if( _error == ERROR_IO_PENDING )
{
DWORD result = ::WaitForMultipleObjects( 2, waiters, FALSE,INFINITE );
switch( result )
{ //Eventshutdown
case WAIT_OBJECT_0: /*code omitted*/break;
case WAIT_OBJECT_0+1: ok = ::GetOverlappedResult( handle, &ov_reader, &bytes_read, true );
//check ok value omitted
break;
}
}
}
}
if( bytes_read>0 )
{
*size = bytes_read;
}
Here starts my problem.
When device sends me small frames (around 30 bytes) everything works fine, but when larger frames are sent, the code is not able to find any free time between frames causing the thread to never be able send any frame because readed is never 0.
If I increase the number of bytes to read inside the read() function, lose the ability to detect when the device "listens":
bool ok = ::ReadFile(handle, buffer_in, 50, &bytes_read, &ov_reader );
This happens because my app can receive the end of a frame together with the start of the next one. This behaviour is very common.
In the other hand, if I change the INFINITE argument by a valid timeout in the WaitForMultipleObjects function, I lose data.
So my question basically is... what I'm doing wrong? Why when reading 1 byte each time I don't find any free time to send my own frames?
Thank you
| I'm not sure if this will help or not, but since you already have a good idea of how many bytes are in the serial device's input queue (stat.cbInQue) maybe it would help to read in that many bytes instead of just 1 byte or an arbitrary number of bytes (like 50):
bool ok = ::ReadFile( handle, buffer_in, stat.cbInQue, &bytes_read, &ov_reader );
Of course, you'd need to make sure that the buffer_in had the capacity for that number of bytes, so there might be some other logic you'd have to add to make sure there's no buffer overruns.
Also, because the serial driver and ReadFile() APIs depend heavily on buffering for handling received characters, you might be able to get more precise indications of when characters have been received (and not received) using the
WaitCommEvent() and SetCommMask() APIs.
|
2,458,372 | 2,458,761 | C++ compile time purity checks? | Is it possible to specify compile time "purity" checks in C++?
I.e.:
this function does not read from anything other than it's arguments
this function does not write to anything; it only returns the return value
| const-correctness and high compiler warning levels should do a lot of what you are asking for. Also specifying a very strict modern dialect of C++ for the compiler ( which can annoy the hell out of you, when you are using third-party libraries and code that dont comply )
If not, then there are a plethora of static analysis tools out there, some open source, some expensive like Coverity, Parasoft C++Test and so on.
|
2,458,381 | 2,458,403 | Using type passed as a template in C++ | Is it possible to actually use the type passed as a template for control flow? I'd like to write a function that uses templates, which in turn calls another function based on the type passed:
template <class T> void test_function (T var)
{
//Do stuff
if (T == char) {
bar (var);
} else {
foo (var);
}
//Do even more stuff
}
If not, I'll have to fallback to enums...
Edit:
All the answers up to now advise me to use template specialization. I wasn't very specific, but this is the same as not using templates at all because for every different type there's a single, different function call.
| You usually use specialization for that:
template<class T> void forward(T t) {
// ...
}
template<> void forward<char>(char c) {
// ...
}
template<class T> void test(T t) {
forward<T>(t);
}
This gives you effectively "compile-time branching".
|
2,458,459 | 2,458,475 | Why friend function is preferred to member function for operator<< | When you are going to print an object, a friend operator<< is used. Can we use member function for operator<< ?
class A {
public:
void operator<<(ostream& i) { i<<"Member function";}
friend ostream& operator<<(ostream& i, A& a) { i<<"operator<<"; return i;}
};
int main () {
A a;
A b;
A c;
cout<<a<<b<<c<<endl;
a<<cout;
return 0;
}
One point is that friend function enable us to use it like this
cout<<a<<b<<c
What other reasons?
| You have to use a free function and not a member function as for binary operators the left hand side is always *this for member functions with the right hand side being passed as the other parameter.
For output stream operators the left hand side is always the stream object so if you are streaming to a standard class and not writing the stream yourself you have to provide a free function and not a member of your class.
Although it would be possible to provide a backwards stream operator as a member function and stream out like this:
myObject >> std::cout;
not only would you violate a very strong library convention, as you point out, chaining output operations would not work due to the left-to-right grouping of >>.
Edit: As others have noted, while you have to make it a free function it only needs to be a friend if the streaming function cannot be implemented in terms of the class' public interface.
|
2,458,617 | 2,458,683 | OO Design - polymorphism - how to design for handing streams of different file types | I've little experience with advanced OO practices, and I want to design this properly as an exercise. I'm thinking of implementing the following, and I'm asking if I'm going about this the right way.
I have a class PImage that holds the raw data and some information I need for an image file. Its header is currently something like this:
#include <boost/filesytem.hpp>
#include <vector>
namespace fs = boost::filesystem;
class PImage
{
public:
PImage(const fs::path& path, const unsigned char* buffer, int bufferLen) :
path_(path), filesize_(bufferLen),
data_(buffer, buffer + filesize_),
width_(0), height_(0) {}
const vector<char> data() const { return data_; }
const char* rawData() const { return &data_[0]; }
/*** other assorted accessors ***/
private:
fs::path path_;
int filesize_;
vector<char> data_;
int width_;
int height_;
}
I want to fill the width_ and height_ by looking through the file's header. The trivial/inelegant solution would be to have a lot of messy control flow that identifies the type of image file (.gif, .jpg, .png, etc) and then parse the header accordingly.
Instead of using vector<char> data_, I was thinking of having PImage use a class, RawImageStream data_ that inherits from vector<char>. Each type of file I plan to support would then inherit from RawImageStream, e.g. RawGifStream, RawPngStream.
Each RawXYZStream would encapsulate the respective header-parsing functions, and PImage would only have to do something like height_ = data_.getHeight();.
Am I thinking this through correctly?
How would I create the proper RawImageStream subclass for data_ to be in the PImage ctor? Is this where I could use an object factory?
Anything I'm forgetting?
| Yes, you could implement your class hierarchy in the way you describe. Nevertheless, I would probably have had PngImage, GifImage and JpegImage derive directly from PImage. PImage can then become abstract:
class PImage
{
virtual ~PImage {}
virtual unsigned int getWidth() const = 0
virtual unsigned int getHeight() const = 0
...
};
Then, each concrete image type implements getWidth and getHeight.
The PImage class can then be created by a PImage factory:
boost::shared_ptr<PImage> createImage(const fs::path& path);
In the factory, you pretty much open the file, look what type it has, and create the concrete image class passing the data in the constructor, to finally return the image as the abstract PImage.
Finally, I'd like to add that you should not worry too much about your design up front, and be ready to refactor later when you discover that your design does not fulfil your needs. That's through trial and error that you will grow a feeling for what design is proper for your problem!
|
2,458,637 | 2,458,665 | Boost link error when using "--layout=system" on VS2005 | I'm new to boost, and thought I'd try it out with some realistic deployment scenarios for the .dlls, so I used the following command to compile/install the libraries:
.\bjam install --layout=system variant=debug runtime-link=shared link=shared
--with-date_time --with-thread --with-regex --with-filesystem
--includedir=<my include directory> --libdir=<my bin directory> > installlog.txt
That seemed to work, but my simple program (taken right from the "Getting Started" page) fails:
#include <boost/regex.hpp>
#include <iostream>
#include <string>
// Place your functions after this line
int main()
{
std::string line;
boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" );
while (std::cin)
{
std::getline(std::cin, line);
boost::smatch matches;
if (boost::regex_match(line, matches, pat))
std::cout << matches[2] << std::endl;
}
}
This fails with the following linker error:
fatal error LNK1104: cannot open file 'libboost_regex-vc80-mt-1_42.lib'
I'm sure that both the .lib and the .dlls are in that directory, and named how I want them to be (ie: boost_regex.lib, etc, all unversioned, as the --layout=system says). So why is it looking for the versioned type of it? And how do I get it to look for the unversioned type of the library?
I've tried this with more "normal" options, such as below:
.\bjam stage --build-type=complete --with-date_time --with-thread --with-filesystem --with-regex > mybuildlog.txt
And that works fine. I made sure my compiler saw the "stage\lib" directory, and it compiled and ran fine with nothing beyond having the environment looking into the right lib directory. But when I took those "testing" directories away, and wanted to use these others (unversioned), then it failed.
I'm under VS2005 here on XP. Any ideas?
| Fast answer, for I have no access to a Visual C++ at home.
I believe you are clashing with the "autolinking" of Boost on Visual C++ compilers.
A solution would be to disable "autolink" (see your documentation for that: A quick google search showed the macro "BOOST_ALL_NO_LIB" to disable autolinking for ALL Boost libraries), and then link explicitely your project to the right library.
I'll update this answer as soon as possible.
|
2,458,917 | 2,458,941 | Passing unknown classes to String Streams in C++ | I am using a template function and I am passing and I may be sending instances of a variety of classes to a string stream. What can I do to make sure this continues to work?
Let me be more specific where do I define the behavior for this? Is there some member that should be on each class being sent to the string stream, should I in some enhance or extend the existing String stream (I was thinking building a class that inherits from sstream and overloads the << operator to handle all the possible classes)?
I had trouble even finding documentation on this, so even links to more resources would be helpful.
| It sounds to me like you want to make stream insertion operators. for a class you want to be able to output to a stream, define the free function:
std::ostream& operator<<(std::ostream& stream, const SomeClassType& x)
{
stream << x.someData();
return stream;
}
So if we have SomeClassType z;, and we do std::cout << z (or any other output stream, like an fstream or stringstream), the compiler will look for and find our function, and call it. That is, std::cout << z becomes operator<<(std::cout, z) and inside there you output what you need.
|
2,458,939 | 2,458,956 | Compile redeclaration error of global variable in C++, but not in C | Suppose that I have those three files:
a.h
//a.h header
#include <stdio.h>
int int_variable;
void a_f()
{
printf("int_variable: %d\n", int_variable)
int_variable++;
}
b.h
//b.h header
#include <stdio.h>
int int_variable;
void b_f()
{
printf("int_variable: %d\n", int_variable)
int_variable++;
}
main.c
//main.c
#include "a.h"
#include "b.h"
int main()
{
a_f();
b_f();
return 0;
}
Why compiling in C++ generates redefinition error, but in C doesn't?
I am C++ developer, then in C++ makes sense to me, but why in C this is not an error?
When I executed the C generated code, the output was:
int variable: 0
int variable: 1
| In C, the two variables are actually combined into a single variable because neither is explicitly initialized.
If you change both your h files to:
// a.h
int int_variable = 0;
and:
// b.h
int int_variable = 0;
you will get a redefinition error.
|
2,459,034 | 2,459,046 | "Undefined Symbols" when inheriting from stdexcept classes | Here is an exception defined in <stdexcept>:
class length_error : public logic_error
{
public:
explicit length_error(const string& __arg);
};
Here is my exception:
#include <string>
#include <stdexcept>
using namespace std;
class rpn_expression_error : public logic_error
{
public:
explicit rpn_expression_error(const string& __arg);
};
Why do I get this error when <stdexcept> does not?
Undefined symbols:
rpn_expression_error::rpn_expression_error(/*string*/ const&), referenced from:
...
ld: symbol(s) not found
At @sbi's request, here is a minimal example of my code at the moment:
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
class RPN_Calculator {
public:
class rpn_expression_error : public logic_error {
public:
explicit rpn_expression_error(const string& arg) : logic_error(arg) {}
};
void Execute() {
throw rpn_expression_error("Hello");
}
};
int main() {
RPN_Calculator calc;
try {
calc.Execute();
} catch (exception e) {
cout << e.what() << endl;
}
}
I saved this as rpn.cpp and ran make rpnto produce the error.
The code now builds completely, however, the real program still gives me the original error.
Note/Solution: Although the code above runs just fine, the same exception class in the real code still produces the linker error. To simplify, I just promoted rpn_expression_error to its own global-scope class, and that seems to have fixed the problem.
| There is a problem with the way you are catching your exceptions. Specifically, consider this code:
struct Base
{
virtual void do() { std::cout << "Base!" << std::endl; }
};
struct Derived : Base
{
virtual void do() { std::cout << "Derived!" << std::endl; }
};
void foo(Base x)
{
x.do();
}
int main()
{
Derived d;
foo(d); // <--
}
On that marked line, d gets what is called "sliced". That is, in order to satisfy being a Base, everything that isn't part of Base gets sliced off! So the above code will output "Base!".
If we want the intended output, we need to make the parameter not a value:
void foo(Base& x) // polymorphic
{
x.do();
}
Our above code would then display "Derived!", because it's no longer being sliced. (One could also use a pointer.)
So, take a look at your catch clause:
catch (exception e)
Here, any exceptions you've thrown will be sliced into the base std::exception class, losing any derived information! This is why it's much more common (and possibly "correct") to catch-by-reference:
catch (const exception& e)
You'll now find e.what() returns the non-sliced error message, as intended.
Old
Here's how the entire thing should look (don't use using namespace in a header!):
// rpn_expression_error.h
#include <stdexcept> // for logic_error
#include <string> // for string
class rpn_expression_error : public std::logic_error
{
public:
explicit rpn_expression_error(const std::string& pMsg);
};
// rpn_expression_error.cpp
#include "rpn_expression_error.h"
rpn_expression_error::rpn_expression_error(const std::string& pMsg) :
std::logic_error(pMsg)
{}
Older
Because those exception classes are declared inside the standard namespace, but yours is not. string is inside the namespace std so they don't need to qualify it, but you do:
#include <string>
// ...
vvv
explicit rpn_expression_error(const std::string& arg);
Keep in mind I've changed your parameter name. Names that contain a double-underscore are reserved, and you shouldn't use them.
|
2,459,057 | 2,459,101 | Array length with pointers | How in C++ get array length with pointers only ? I know that tab name is pointer to first element, but what next ?
| You cannot. A pointer is just a memory location, and contains nothing special that could determine the size.
Since this is C++, what you can do is pass the array by reference like so:
template <typename T, size_t N>
void handle_array(T (&pX)[N])
{
// the size is N
pX[0] = /* blah */;
// ...
pX[N - 1] = /* blah */;
}
// for a specific type:
template <size_t N>
void handle_array(int (const &pX)[N]) // const this time, for fun
{
// the size is N
int i = pX[0]; // etc
}
But otherwise you need to pass start & end and do a subtraction, like Alok suggests, a start & size, like you suggest, or ditch a static array and use a vector, like Tyler suggests.
If you know the size of the array you'll be working with, you can make a typedef:
typedef int int_array[10];
void handle_ten_ints(int_array& pX)
{
// size must be 10
}
And just for the size:
template <typename T, size_t N>
size_t countof(T (&pX)[N])
{
return N;
}
template <typename T, size_t N>
T* endof(T (&pX)[N])
{
return &pX[0] + N;
}
// use
int someArray[] = {1, 2, 6, 2, 8, 1, 3, 3, 7};
size_t count = countof(someArray); // 9
std::for_each(someArray, endof(someArray), /* ... */);
I use these utility functions from time to time.
|
2,459,550 | 2,459,558 | How can I print a NUL character without a space in C? | I have a situation where I have to print out a NUL character if there is no action in a part of my program. Take for example the code below:
char x = '\0';
...
printf("@%c@\n", x);
I want it to print this:
@@
but it prints out
@ @
Whats the correct way not to have the \0 character printed out a space as above?
| if (x == 0)
printf("@@\n");
else
printf("@%c@\n", x);
It's not actually printing a space, it actually outputs the \0. It's just that whatever you're viewing the text with is displaying the \0 as a space.
|
2,459,588 | 2,483,454 | Pass by reference in Boost::Python | Consider something like:
struct Parameter
{
int a;
Parameter(){a = 0;}
void setA(int newA){a = newA;}
};
struct MyClass
{
void changeParameter(Parameter &p){ p.setA(-1);}
};
Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instantiate an object of Parameter in the C++ code, which I pass to the python script, and that python script uses a MyClass object to modify the instance of Parameter I created at the beginning in the C++ code.
After that code executes, in C++ Parameter instance is unchanged!!! This means it was passed by value (or something alike :S), not by reference. But I thought I declared it to be passed by reference...
I can't seem to find Boost::Python documentation about passing by reference (although there seems to be enough doc about returning by reference...). Can anyone give some hint or pointer please?
| Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object.
In this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.
|
2,459,607 | 2,459,886 | A quick design question about C++ container classes in shared memory | I am writing a simple wrapper around boost::interprocess's vector container to implement a ring buffer in shared memory (shm) for IPC. Assume that buf is an instance of RingBuffer created in shm. Now, in its ctor, buf itself allocates a private boost::interprocess::vector data member to store values, e.g. m_data. My question is: I think m_data should also be created in shared memory. But it this a necessity?
What happens if buf that was created in shm itself, allocates standard memory, i.e. using new. Does this get allocated on the calling process's heap? I don't think buf is allocated there so how come a data member that is private to an object not on a process's heap gets allocated there. I'm confused.
| boost::interprocess::vector takes an allocator type as a template parameter. This allocator needs to allocate from the shared memory (see the examples of use).
If you class allocates memory with new, then that memory will only be accessible from the process it was allocated in. This is wrong, and is exactly why boost::interprocess::vector needs a shared memory allocator.
in its ctor, buf itself allocates a private boost::interprocess::vector data member
This doesn't make sense to me. In C++, you cannot "allocate" a data member in a constructor. Data members are defined in the class body, and they are part of each object of that class. They're in the same memory the object is, for the same reason that the middle byte of a 4-byte integer is in the same memory that the integer is.
how come a data member that is private to an object not on a process's heap gets allocated there
Memory is allocated how you ask for it to be allocated. If you allocate with new (and it hasn't been overloaded), then it's allocated in process memory. If you allocate with a shared memory segment manager (which is what I think Boost calls it - I haven't actually used those APIs myself), it's allocated in shared memory. The class which contains the call, and the data member where you store the pointer to the allocated memory, have nothing to do with it.
|
2,459,755 | 2,459,782 | Why can't we have an immutable version of operator[] for map | The following code works fine :
std::map<int, int>& m = std::map<int, int>();
int i = m[0];
But not the following code :
// error C2678: binary '[' : no operator...
const std::map<int, int>& m = std::map<int, int>();
int i = m[0];
Most of the time, I prefer to make most of my stuff to become immutable, due to reason :
http://www.javapractices.com/topic/TopicAction.do?Id=29
I look at map source code. It has
mapped_type& operator[](const key_type& _Keyval)
Is there any reason, why std::map unable to provide
const mapped_type& operator[](const key_type& _Keyval) const
| operator[] will create the entry if it does not exist in the map. This is not possible if the operator is implemented for a const map. This is the explanation given in The C++ Programming Language:
Subscripting a map adds a default
element when the key is not found.
Therefore, there is no version of operator[] for const maps.
Furthermore, subscripting can be
used only if the mapped_type (value
type) has a default value. If the
programmer simply wants to see if a
key is present, the find() operation
(§17.4.1.6) can be used to locate a
key without modifying the map.
|
2,459,776 | 2,460,089 | C++: type Length from float | This is kinda like my earlier question:
C++: Vector3 type "wall"?
Except, now, I want to do this to a builtin rather then a user created type.
So I want a type "Length" that behaves just like float -- except I'm going to make it's constructor explicit, so I have to explicitly construct Length objects (rather than have random conversions flying around).
Basically, I'm going into the type-a-lot camp.
| It sounds like you want to wrap a float primitive in your own class. Here's an example to get you started:
class Length
{
protected:
float value_;
public:
Length(float value) : value_(value) { }
static Length operator +(Length a, Length b) { return Length(a.value_ + b.value_); }
static Length operator -(Length a, Length b) { return Length(a.value_ - b.value_); }
static Length operator *(Length a, Length b) { return Length(a.value_ * b.value_); }
static Length operator /(Length a, Length b) { return Length(a.value_ / b.value_); }
};
But, using the boost Units library is a much better choice in the long run...
|
2,459,800 | 2,459,815 | How can I break if gdb is attached, but continue if it is not? | I have some debugging code that if executed while running with GBD attached should break the execution of the application, but if GDB is not running it should continue.
The code I'm working with looks something like this in structure:
try
{
if( some_complex_expression )
{
gdb_should_break_here();
do_some_stuff();
throw MyException();
}
}
catch( const MyException & e )
{
handle_exception_and_continue();
}
What should gdb_should_break_here be?
| Actually it looks like just making sure there is an empty gdb_should_break_here() function everywhere I need to break will work. (So long as I'm not optimising the code).
Then all I need to do is a
break gdb_should_break_here
and gdb will stop in all the right places.
Guess I overlooked it as my code wasn't really that nicely organised, and contained in a few debugging macros.
|
2,459,809 | 2,461,694 | Convert CString array to System::String | I want to convert CString array to managed code ot send it to C#.
For normal CString i did like this,
CString menu = "MENU";
String ^ msg = gcnew String(menu);
Globals1::gwtoolbar->Add(msg);
But now i want to send array of string.i dont know how to do for CString array.
When i gave like this it shows error
CString menu[10];
String[] ^ msg = gcnew String(menu);
How can i convert it?
| Given:
CString menu[10]
To convert to a managed array of String:
#DEFINE MENU_COUNT 10;
array<String^>^ clrMenu = gcnew array<String^>(MENU_COUNT);
for (int i = 0; i < MENU_COUNT; ++i)
{
clrMenu[i] = gcnew String(menu[i]);
}
|
2,459,999 | 2,460,083 | Planning a programming project by example (C# or C++) | I am in the last year of undergraduate degree and i am stumped by the lack of example in c++ and c# large project in my university. All the mini project and assignment are based on text based database, which is so inefficient, and console display and command, which is frustrating.
I want to develop a complete prototype of corporate software which deals in Inventory, Sales, Marketing, etc. Everything you would usually find in SAP. I am grateful if any of you could direct me to a books or article or sample program.
Some of the question are :
How to plan for this kind of programming? should i use the concept of 1 object(such as inventory) have its own process and program and have an integrator sit for all the program, or should i integrate it in 1 big program?
How to build and address a database? i have little bit knowledge in database and i know SQL but i never address database in a program before. Database are table, and how do you suppose to represent a table in a OOP way?
For development type, which is better PHP and C++ or C# and ASP.NET? I am planning to use Web Interface to set form and information, but using a background program to handle the compute. .NET is very much integrated and coding should be much faster, but i really wonder about performance if compared to PHP and C++ package
thank you for the info
| Before I start this is a shallow answer to a deep question.
1) It looks like you have a reasonable grasp of the major components of your target application. As a .net developer I'd build assemblies that matched broad areas of functionality (not sure what the equivalent is in PHP) and then you can use those assemblies together as a single large app, or seperately as required. It's unlikely you'll get it right first time, so build it how it feels right, and then do some ruthless refactoring to make it better once you've got a handled on the problem.
2) This whole area is covered by Object Relational Mapping - ORM, NHibernate is the best of the bunch in the .Net world. BTW if you learn that you'll be way ahead of the game come graduation/work time. Raw sql is so last decade. I guess you know that Sql Server Express is a free download?
3) For development go with the languages/environment you feel most comfortable in. My preference is .net, and the integrated coding is much faster. Performance is definitely good enough, especially as this is learning project - SO runs on .Net and that supports a gazillion users pretty well.
Enjoy
|
2,460,376 | 2,460,597 | How might I assume a "default value" when parsing using boost::spirit? | Let's say I have a grammar defined to something like:
some_rule := a b [c [d]]
where c, and d are optional and default to a certain value (let's say 14) if not given. Can I get it to default to the 14 if the value isn't given? I want the produced std::vector to always be of size 4.
The closest I've come is like the following:
qi::rule<Iterator, std::vector<int>(), ascii::space_type> some_rule;
some_rule %= int_ >> int_ >> -int_ >> -int_;
// ...
some_other_rule = some_rule[&some_callback_for_int_vectors];
which will then get 0 for the optional values that didn't show up (I believe). I then change consecutive 0s at the end into 14. Not only is this horribly wrong, but it's also just not elegant. Is there a better way to do this?
| It looks like you can do this with the boost::qi::attr auxiliary parser.
int default_value = 14;
qi::rule<Iterator, int(), ascii::space_type> some_optional_rule;
qi::rule<Iterator, std::vector<int>(), ascii::space_type> some_rule;
some_optional_rule %= int_ | attr(default_value);
some_rule %= repeat(2)[int_] >> repeat(2)[some_optional_rule];
I'm still not sure if this is the best way to do this though.
|
2,460,402 | 2,460,567 | Tutorials for an experienced C# user to learn C++ | Are there any good resources for learning C++ that a C# user could use, which don't require knowledge of C?
I have quite a good knowledge of C# via courses in my University's game development program (in a 300 level course right now) but now I need to use C++ for a project.
I would use a beginner tutorial but they are so hard for me to follow and learn the basic syntax because they start so slowly.
I found a few of tutorials for switching from C++ to C#, but none in the other direction. I do have a little bit of Objective C practice from iPhone programming as well.
| There are lots of resources titled C# for C++ programmers.
You can use them ;) You will come to know what are the things you are going to miss
when you move from C# to C++.
C++ vs. C# - a Checklist from a C++ Programmers Point of View.
Learn some syntax first and then some STL. In a week you will feel comfortable.
But there is no need to start from scratch because C# borrows a lot from C++.
|
2,460,417 | 2,460,439 | How to partition bits in a bit array with less than linear time | This is an interview question I faced recently.
Given an array of 1 and 0, find a way to partition the bits in place so that 0's are grouped together, and 1's are grouped together. It does not matter whether 1's are ahead of 0's or 0's are ahead of 1's.
An example input is 101010101, and output is either 111110000 or 000011111.
Solve the problem in less than linear time.
Make the problem simpler. The input is an integer array, with each element either 1 or 0. Output is the same integer array with integers partitioned well.
To me, this is an easy question if it can be solved in O(N). My approach is to use two pointers, starting from both ends of the array. Increases and decreases each pointer; if it does not point to the correct integer, swap the two.
int * start = array;
int * end = array + length - 1;
while (start < end) {
// Assume 0 always at the end
if (*end == 0) {
--end;
continue;
}
// Assume 1 always at the beginning
if (*start == 1) {
++start;
continue;
}
swap(*start, *end);
}
However, the interview insists there is a sub-linear solution. This makes me thinking hard but still not get an answer.
Can anyone help on this interview question?
UPDATE: Seeing replies in SO stating that the problem cannot be solved in sub-linear time, I can confirm my original idea that there cannot be a solution of sub-linear.
Is it possible the interviewer plays a trick?
| I don't see how there can be a solution faster than linear time.
Imagine a bit array that is all 1's. Any solution will require examining every bit in this array before declaring that it is already partitioned. Examining every bit takes linear time.
|
2,460,537 | 2,460,628 | Generating tuples from tuples | Say you have a tuple and want to generate a new tuple by applying a metafunction on each type of the first one. What' the most efficient C++ metafuntion to accomplish to this task? Is it also possible to use C++0x variadic template to provide a better implementation?
| How 'bout this one:
template<typename Metafun, typename Tuple>
struct mod;
// using a meta-function class
template<typename Metafun, template<typename...> class Tuple, typename ...Types>
struct mod<Metafun, Tuple<Types...>> {
typedef Tuple<typename Metafun::template apply<Types>::type...>
type;
};
Then
typedef std::tuple<int, bool> tuple_foo;
struct add_pointer {
template<typename T>
struct apply { typedef T *type; };
};
typedef mod<add_pointer, tuple_foo>::type tuple_ptrfoo;
That's using a metafunction class by wrapping the apply into a non-template. That allows passing it to C++03 templates (which cannot accept templates with arbitrary parameters by simply doing template<typename...> class X). You may, of course, accept a pure metafunction (not a class) too
template<template<typename...> class Metafun, typename Tuple>
struct mod;
// using a meta-function
template<template<typename...> class Metafun, template<typename...> class Tuple,
typename ...Types>
struct mod<Metafun, Tuple<Types...>> {
typedef Tuple<typename Metafun<Types>::type...>
type;
};
And use the std::add_pointer template
typedef mod<std::add_pointer, tuple_foo>::type tuple_ptrfoo;
Or you can wrap it into a class so it is compatible with the first version
// transforming a meta function into a meta function class
template<template<typename...> class Metafun>
struct ToClass {
template<typename ... T>
struct apply { typedef Metafun<T...> type; };
};
typedef mod<ToClass<std::add_pointer>, tuple_foo>::type tuple_ptrfoo;
Hope it helps.
|
2,460,549 | 2,461,291 | Deriving streambuf or basic_ostringstream? | I want to derive a stringstream so that I can use the operator<< to construct a message which will then be thrown. The API would look like:
error("some text") << " more text " << 42 << std::endl;
This should do a
throw "some text more text 42"
So what I did is make an errorbuf (inheriting from streambuf) which overloads the 'overflow' method and then create an ostream(&errorbuf). I wonder if I shouldn't instead inherit from basic_ostringstream or something...
| I'll trot out my favourite macro again here:
#define ATHROW( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw ALib::Exception( os.str(), __LINE__, __FILE__ ); \
} \
In use:
ATHROW( "Invalid value: " << x << " should be " << 42 );
the exception type is from my own library, but I think you get the idea. This is much simpler than deriving your own stream class, and avoids lots of nasty complications with op<<().
|
2,460,571 | 2,460,578 | Cannot convert CString to BYTE array | I need to convert CString to BYTE array. I don't know why, but everything that I found in internet does not work :(
For example, I have
CString str = _T("string");
I've been trying so
1)
BYTE *pbBuffer = (BYTE*)(LPCTSTR)str;
2)
BYTE *pbBuffer = new BYTE[str.GetLength()+1];
memcpy(pbBuffer, (VOID*)(LPCTSTR)StrRegID, str.GetLength());
3)
BYTE *pbBuffer = (BYTE*)str.GetString();
And always pbBuffer contains just first letter of str
DWORD dwBufferLen = strlen((char *)pbBuffer)+1;
is 2
But if I use const string:
BYTE *pbBuffer = (BYTE*)"string";
pbBuffer contains whole string
Where is my mistake?
| Your CString is Unicode (two bytes per character) and you try to interpret it as ANSI (one byte per character). This leads to results you don't expect.
Instead of casting the underlying buffer into char* you need to convert the data. Use WideCharToMultiByte() for that.
|
2,460,944 | 2,461,041 | Window interface instead of console in c | I have console application in c. I want to convert into window application, kindly guide me so that I can make it possible.
| Outline of steps you need to take:
replace main with WinMain
change subsystem from Console to Window
create a main window or a dialog (resource editor may come handy here), and its corresponding procedure
create a message loop
change a structure of your program to be executed in a loop (the program should be always responsible)
or execute the "serial console-like" program in a separare thread, just sending its output into the "window"
First two are quite easy, the most work lies in the next steps. if you want the window be just your own replication of a console, you can design a dialogue containing one text or edit control, and implement a simple dialog procedure and a message loop. Some code snippets follow, but giving a complete and working sample would go beyond the reasonable space. If you understand the code below, I guess it should get you started. If not, I am afraid you will have to learn Windows progamming basics first.
Dialog procedure
HWND consoleEditHWnd;
static int CALLBACK ConsoleDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
InitWindow((HINSTANCE)hInstApp,hDlg);
consoleEditHWnd = GetDlgItem(hDlg,IDC_CONSOLE_EDIT);
return TRUE;
}
case WM_SIZE:
if (consoleEditHWnd)
{
RECT rect;
GetClientRect(hDlg, &rect);
MoveWindow(
consoleEditHWnd, rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, TRUE
);
}
break;
}
return FALSE;
}
Dialog creation and a message loop
hwndApp = CreateDialog(hInst, MAKEINTRESOURCE(IDD_CONSOLE), NULL, ConsoleDlgProc);
ShowWindow((HWND)hwndApp,SW_SHOW);
UpdateWindow((HWND)hwndApp);
MSG msg;
while( PeekMessage(&msg, 0, 0, 0, PM_REMOVE) )
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Writing into the console
When you want to add some text into the "console", you can do it using
int count = GetWindowTextLengthW(consoleEditHWnd);
... allocate a buffer
GetWindowTextW(consoleEditHWnd,buffer,count+newTextSize);
... append
SetWindowTextW(consoleEditHWnd,buffer);
|
2,460,953 | 2,461,212 | Is there any simple way to determine when the popup menu was dismissed? | I'm displaying a popup menu using TrackPopupMenu and would like to know when it is dismissed via clicking outside of it. I've looked through all the menu functions but didn't find anything useful in this regard. Spy++ told me that no window message is sent in this case.
So, is there an easy way to do it without installing a mouse hook? Thanks!
| [edit]
This is better.
If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.
The menu loop is ended when ::TrackPopupMenu() returns :)
If a menu item was selected the window having the HWND passed as 6th parameter will receive a WM_COMMAND message with the ID of the selected item. You can probably ::PeekMessage() after ::TrackPopupMenu() returns to see if WM_COMMAND is in the queue.
If you want to be notified while in ::TrackPopupMenu() you can handle WM_EXITMENULOOP.
|
2,461,111 | 2,462,783 | Are the following two statements semantically same? | Are the following two statements semantically same?
#1 person p("Rahul", 20);
#2 person const &p = person("Rahul", 20);
EDIT:
Sorry, I meant to ask whether the following two are semantically same:
#1 person const p("Rahul", 20);
#2 person const &p = person("Rahul", 20);
| They are not. However, the difference are affected only by the fact that the second case needs a copy constructor to be accessible in C++03 (even if the copy constructor call is not actually done)
// works with #1 fails with #2
struct f1 { f1(string, int); private: f1(f1 const&); };
|
2,461,272 | 2,461,375 | which is preferd use istrstream or strtol/strtod for reading number from string | I have to read number from string .which one is safe and preferred
istrstream
atoi/atof
strtol/strto
Please guide me.
| Why use <iostream> instead of <cstdio> ?
Increase type safety, reduce errors, allow extensibility, and provide inheritability.
printf() is arguably not broken, and scanf() is perhaps livable despite being error prone, however both are limited with respect to what C++ I/O can do. C++ I/O (using << and >>) is, relative to C (using printf() and scanf()):
More type-safe: With <iostream>, the
type of object being I/O'd is known
statically by the compiler. In
contrast, <cstdio> uses "%" fields to
figure out the types dynamically.
Less error prone: With <iostream>,
there are no redundant "%" tokens
that have to be consistent with the
actual objects being I/O'd. Removing
redundancy removes a class of errors.
Extensible: The C++ <iostream>
mechanism allows new user-defined
types to be I/O'd without breaking
existing code. Imagine the chaos if
everyone was simultaneously adding
new incompatible "%" fields to
printf() and scanf()?!
Inheritable:
The C++ <iostream> mechanism is built
from real classes such as
std::ostream and std::istream. Unlike
<cstdio>'s FILE*, these are real
classes and hence inheritable. This
means you can have other user-defined
things that look and act like
streams, yet that do whatever strange
and wonderful things you want. You
automatically get to use the zillions
of lines of I/O code written by users
you don't even know, and they don't
need to know about your "extended
stream" class.
|
2,461,559 | 2,462,184 | Are L'A' and 'A' totally same? | When we write a program which supports both unicode and multibytes,
we often use _T("some string") macro for strings.
But, does a character also need to wrap this macro?
Are L'A' and 'A' totally same?
Don't we need to wrap _T('A') for a character?
| If you write 'A', and that value gets converted to wchar_t, then on Microsoft compilers at least, it will have the same value as if you'd written L'A' or _T('A').
The same can't be said of string literals, since there is no useful conversion from const char* to const wchar_t*. I think this means it's rather less important to get character literal types right, than string literals.
It's easy to write code that behaves differently according to whether a character literal is wide or narrow - just have an overloaded function that does something completely different. But in practice, sensible functions overloaded to take both types of character are going to end up doing the same thing with 'A' that they do with L'A'. And functions which aren't overloaded, and only take wchar_t, can take 'A' just fine.
I don't immediately see anything in the standard to require that L'A' == (wchar_t)'A', so in theory non-Microsoft compilers might do something completely different. But you'd normally expect the wide character set to be an extension of the narrow character set, just as Unicode extends ISO-8859-1. To be specific what "extension" means, code points which are equal as integers designate the "same character".
|
2,461,630 | 2,461,676 | Why this works (Templates, SFINAE). C++ | referring to yesterday's post,
this woke me up this morning. Why does this actually work? As long as the function test is concerned, this function has no body so how can it perform anything? I want to know why and how this works? I'm REALLY interested to see your answers.
template<typename T>
class IsClassT {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*); //NO BODY HERE
template<typename C> static Two test(…); //NOR HERE
public:
enum { Yes = sizeof(IsClassT<T>::template test<T>(0)) == sizeof(One) };
enum { No = !Yes };
};
Thanks in advance with help to understand this very interesting phenomenon.
| I assume you are refering to the Yes enum? IsClassT<T>::test<T>(0)? sizeof does not actually evaluate its arguments. That's why code like the following is legal, even though you might expect it to bail out on you:
int* p = 0;
int sizeof_int = sizeof(*p); //oops, p is 0 :(
|
2,461,880 | 2,469,088 | Writing a Makefile.am to invoke googletest unit tests | I am trying to add my first unit test to an existing Open Source project. Specifically, I added a new class, called audio_manager:
src/audio/audio_manager.h
src/audio/audio_manager.cc
I created a src/test directory structure that mirrors the structure of the implementation files, and wrote my googletest unit tests:
src/test/audio/audio_manager.cc
Now, I am trying to set up my Makefile.am to compile and run the unit test:
src/test/audio/Makefile.am
I copied Makefile.am from:
src/audio/Makefile.am
Does anyone have a simple recipe for me, or is it to the cryptic automake documentation for me? :)
| William's answer got me where I needed to go. Just for the sake of the community, here's what I ended up doing:
I moved my tests back into the main directory structure and prepended test_, as per William's suggestions.
I added a few lines to src/audio/Makefile.am to enable unit tests:
# Unit tests
noinst_PROGRAMS = test_audio_manager
test_audio_manager_SOURCES = $(libadonthell_audio_la_SOURCES) test_audio_manager.cc
test_audio_manager_CXXFLAGS = $(libadonthell_audio_la_CXXFLAGS)
test_audio_manager_LDADD = $(libadonthell_audio_la_LIBADD) -lgtest
TESTS = test_audio_manager
Now, running "make check" fires the unit tests!
All of this can be seen here: http://github.com/ksterker/adonthell/commit/aacdb0fe22f59e61ef0f5986827af180c56ae9f3
|
2,461,924 | 2,462,135 | Debugging instance of another thread altering my data | I have a huge global array of structures. Some regions of the array are tied to individual threads and those threads can modify their regions of the array without having to use critical sections. But there is one special region of the array which all threads may have access to. The code that accesses these parts of the array needs to carefully use critical sections (each array element has its own critical section) to prevent any possibility of two threads writing to the structure simultaneously.
Now I have a mysterious bug I am trying to chase, it is occurring unpredictably and very infrequently. It seems that one of the structures is being filled with some incorrect number. One obvious explanation is that another thread has accidentally been allowed to set this number when it should be excluded from doing so.
Unfortunately it seems close to impossible to track this bug. The array element in which the bad data appears is different each time. What I would love to be able to do is set some kind of trap for the bug as follows: I would enter a critical section for array element N, then I know that no other thread should be able to touch the data, then (until I exit the critical section) set some kind of flag to a debugging tool saying "if any other thread attempts to change the data here please break and show me the offending patch of source code"... but I suspect no such tool exists... or does it? Or is there some completely different debugging methodology that I should be employing.
| How about wrapping your data with a transparent mutexed class? Then you could apply additional lock state checking.
class critical_section;
template < class T >
class element_wrapper
{
public:
element_wrapper(const T& v) : val(v) {}
element_wrapper() {}
const element_wrapper& operator = (const T& v) {
#ifdef _DEBUG_CONCURRENCY
if(!cs->is_locked())
_CrtDebugBreak();
#endif
val = v;
return *this;
}
operator T() { return val; }
critical_section* cs;
private:
T val;
};
As for critical section implementation:
class critical_section
{
public:
critical_section() : locked(FALSE) {
::InitializeCriticalSection(&cs);
}
~critical_section() {
_ASSERT(!locked);
::DeleteCriticalSection(&cs);
}
void lock() {
::EnterCriticalSection(&cs);
locked = TRUE;
}
void unlock() {
locked = FALSE;
::LeaveCriticalSection(&cs);
}
BOOL is_locked() {
return locked;
}
private:
CRITICAL_SECTION cs;
BOOL locked;
};
Actually, instead of custom critical_section::locked flag, one could use ::TryEnterCriticalSection (followed by ::LeaveCriticalSection if it succeeds) to determine if a critical section is owned. Though, the implementation above is almost as good.
So the appropriate usage would be:
typedef std::vector< element_wrapper<int> > cont_t;
void change(cont_t::reference x) { x.lock(); x = 1; x.unlock(); }
int main()
{
cont_t container(10, 0);
std::for_each(container.begin(), container.end(), &change);
}
|
2,461,977 | 2,462,019 | Issue compiling c++ in c++builder | I have written a C++ program for a University assignment. I used Netbeans 6.8 running on my Mac and the code runs smoothly, no warnings, errors or problems/bugs. However when compiling and running on a Windows computer using CodeGear RAD Studio 2009 (C++ Builder) am getting several errors.
[BCC32 Error] main.cpp(51): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string'
[BCC32 Error] main.cpp(62): E2093 'operator==' not implemented in type 'string' for arguments of the same type
[BCC32 Error] main.cpp(67): E2093 'operator==' not implemented in type 'string' for arguments of the same type
[BCC32 Error] main.cpp(112): E2093 'operator==' not implemented in type 'string' for arguments of the same type
[BCC32 Error] main.cpp(121): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string'
[BCC32 Error] main.cpp(130): E2093 'operator==' not implemented in type 'string' for arguments of the same type
[BCC32 Error] main.cpp(133): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string'
[BCC32 Error] main.cpp(139): E2094 'operator<<' not implemented in type 'ostream' for arguments of type 'string'
[BCC32 Error] main.cpp(153): E2094 'operator<<' not implemented in type 'fstream' for arguments of type 'string'
[BCC32 Error] main.cpp(199): E2094 'operator>>' not implemented in type 'fstream' for arguments of type 'string'
[BCC32 Error] main.cpp(219): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string'
[BCC32 Error] main.cpp(231): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string'
[BCC32 Error] main.cpp(240): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string'
[BCC32 Error] main.cpp(262): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string'
[BCC32 Error] main.cpp(264): E2094 'operator>>' not implemented in type 'istream' for arguments of type 'string'
These are the header files am using
#include <iostream>
#include <fstream>
#include <cmath>
#include <stdio>
#include <windows> //I added this one just to check and still does not work (I didnt have it on Netbeans/Mac)
using namespace std;
Any ideas what is producing the errors and how can I fix it?
| You need:
#include <string>
and it's:
#include <windows.h>
though I doubt you need it.
The reason your code worked on one platform but not another is that on the first platform one of the other library headers was including <string> itself. This behaviour is not specified by the C++ Standard, so the only safe rule is:
If you use a class or a function,
always explicitly #include the header
for that class or function in your
code.
|
2,462,233 | 2,462,301 | Safe way for getting/finding a vertex in a graph with custom properties -> good programming practice? | I am writing a Graph-class using boost-graph-library. I use custom vertex and edge properties and a map to store/find the vertices/edges for a given property.
I'm satisfied with how it works, so far.
However, I have a small problem, where I'm not sure how to solve it "nicely".
The class provides a method
Vertex getVertex(Vertexproperties v_prop)
and a method
bool hasVertex(Vertexproperties v_prop)
The question now is, would you judge this as good programming practice in C++?
My opinion is, that I have first to check if something is available before I can get it.
So, before getting a vertex with a desired property, one has to check if hasVertex() would return true for those properties.
However, I would like to make getVertex() a bit more robust. ATM it will segfault when one would directly call getVertex() without prior checking if the graph has a corresponding vertex. A first idea was to return a NULL-pointer or a pointer that points past the last stored vertex. For the latter, I haven't found out how to do this.
But even with this "robust" version, one would have to check for correctness after getting a vertex or one would also run into a SegFault when dereferencing that vertex-pointer for example.
Therefore I am wondering if it is "ok" to let getVertex() SegFault if one does not check for availability beforehand?
| I would either change this to:
bool getVertex(Vertex& vertex, Vertexproperties v_prop);
or have getVertex raise an exception if the vertex is not found.
|
2,462,624 | 2,462,665 | How can I find out what the current charset is in C++? | How can I find out what the current charset is in C++?
In a console application (WinXP) I am getting negative values for some characters (like äöüé) with
(int)mystring[a]
and this surprises me. I was expecting the values to be between 127 and 256.
So is there something like GetCharset() or SetCharset() in c++?
| It depends on how you look at the value you have at hand. char can be signed(e.g. on Windows), or unsigned like on some other systems. So, what you should do is to print the value as unsigned to get what you are asking for.
C++ until now is char-set agnostic. For Windows console specifically, you can use: GetConsoleOutputCP.
|
2,462,737 | 2,463,173 | c++, object life-time of anonymous (unnamed) variables | In the following code, the object constructed in the last line of 'main()', seems to be destroyed before the end of the expression. The destructor is called before the '<<' is executed. Is this how it is supposed to be?
#include <string>
#include <sstream>
#include <iostream>
using std::string;
using std::ostringstream;
using std::cout;
class A : public ostringstream
{
public:
A () {}
virtual ~A ()
{
string s;
s = str();
cout << "from A: " << s << std::endl;
}
};
int
main ()
{
string s = "Hello";
A os;
os << s;
cout << os.str() << std::endl;
A() << "checking this";
}
This is the output:
Hello
from A: 0x80495f7
from A: Hello
This is the gdb log:
(gdb) b os.cxx : 18
Breakpoint 1 at 0x80492b1: file os.cxx, line 18. (2 locations)
(gdb) r
Starting program: /home/joe/sandbox/test/os
Hello
Breakpoint 1, ~A (this=0xbffff37c, __in_chrg=<value optimized out>, __vtt_parm=<value optimized out>) at os.cxx:18
18 cout << "from A: " << s << std::endl;
(gdb) p s.c_str ()
$1 = 0x804b45c "0x80495f7"
(gdb) p *s.c_str ()
$2 = 48 '0'
(gdb) c
Continuing.
from A: 0x80495f7
Breakpoint 1, ~A (this=0xbffff2bc, __in_chrg=<value optimized out>, __vtt_parm=<value optimized out>) at os.cxx:18
18 cout << "from A: " << s << std::endl;
(gdb) p s.c_str ()
$3 = 0x804b244 "Hello"
(gdb) p *s.c_str ()
$4 = 72 'H'
(gdb) c
Continuing.
from A: Hello
Program exited normally.
(gdb)
| I believe the behavior that you are seeing is because of the rule that "anonymous temporaries cannot be passed into functions as non-const references" (well not really NOT, but have undefined behavior or different behavior on different compilers). Thus, it does go to the << operator at the last line, but it finds the member(const void*) overload for the << operator rather than the free function (const char*) overload, mainly because of the rule stated above. Thus, a temporary A is constructed, and passed to the << operator which returns a non-const reference.
Thus, now the operator<<(const void*) is defined as a member of the class while operator<<(const char*) is a free function. When a function is called on a non-const temporary, the only function that matches the argument is looked up in the member functions and no free functions are matched to it. I know for a fact that MSVC has different behaviour to GCC.
Infact if you try changing the string "checking this" to something smaller so you can see its value (convert it from char* to void* and see what value you get), you will see that what it is printing is actually void* cast of "checking this". So the destructor is called at the very end, but the << has cast the char* to void* and that is what is printed.
|
2,462,773 | 2,462,819 | C++ copy-construct construct-and-assign question | Here is an extract from item 56 of the book "C++ Gotchas":
It's not uncommon to see a simple
initialization of a Y object written
any of three different ways, as if
they were equivalent.
Y a( 1066 );
Y b = Y(1066);
Y c = 1066;
In point of fact, all three of these
initializations will probably result
in the same object code being
generated, but they're not equivalent.
The initialization of a is known as a
direct initialization, and it does
precisely what one might expect. The
initialization is accomplished through
a direct invocation of Y::Y(int).
The initializations of b and c are
more complex. In fact, they're too
complex. These are both copy
initializations. In the case of the
initialization of b, we're requesting
the creation of an anonymous temporary
of type Y, initialized with the value
1066. We then use this anonymous temporary as a parameter to the copy
constructor for class Y to initialize
b. Finally, we call the destructor for
the anonymous temporary.
To test this, I did a simple class with a data member (program attached at the end) and the results were surprising. It seems that for the case of c, the object was constructed by the copy constructor rather than as suggested in the book.
Does anybody know if the language standard has changed or is this simply an optimisation feature of the compiler? I was using Visual Studio 2008.
Code sample:
#include <iostream>
class Widget
{
std::string name;
public:
// Constructor
Widget(std::string n) { name=n; std::cout << "Constructing Widget " << this->name << std::endl; }
// Copy constructor
Widget (const Widget& rhs) { std::cout << "Copy constructing Widget from " << rhs.name << std::endl; }
// Assignment operator
Widget& operator=(const Widget& rhs) { std::cout << "Assigning Widget from " << rhs.name << " to " << this->name << std::endl; return *this; }
};
int main(void)
{
// construct
Widget a("a");
// copy construct
Widget b(a);
// construct and assign
Widget c("c");
c = a;
// copy construct!
Widget d = a;
// construct!
Widget e = "e";
// construct and assign
Widget f = Widget("f");
return 0;
}
Output:
Constructing Widget a
Copy constructing Widget from a
Constructing Widget c
Assigning Widget from a to c
Copy constructing Widget from a
Constructing Widget e
Constructing Widget f
Copy constructing Widget from f
I was most surprised by the results of constructing d and e. To be precise, I was expecting an empty object to be created, and then an object to be created and assigned to the empty object. In practice, the objects were created by the copy constructor.
| The syntax
X a = b;
where a and b are of type X has always meant copy construction. Whatever variants, such as:
X a = X();
are used, there is no assignment going on, and never has been. Construct and assign would be something like:
X a;
a = X();
|
2,462,795 | 2,475,567 | Is UTC or local time used with time-based notifications? | I have a time in the future when I want a notification to occur and need to know if ::CeSetUserNotificationEx expects UTC or local time in the stStartTime field of the CE_NOTIFICATION_TRIGGER structure if the dwType field is set to CNT_TIME?
| After actually testing ::CeSetUserNotificationEx with both UTC and local time input, I'm in the position of answering my own question:
::CeSetUserNotificationEx wants local time.
|
2,462,845 | 2,462,923 | Implement abstract class as a local class? pros and cons | for some reason I'm thinking on implementing interface within a some function(method) as local class.
Consider following:
class A{
public:
virtual void MethodToOverride() = 0;
};
A * GetPtrToAImplementation(){
class B : public A {
public:
B(){}
~B(){}
void MethodToOverride() {
//do something
}
};
return static_cast<A *>(new B());
}
int _tmain(int argc, _TCHAR* argv[])
{
A * aInst = GetPtrToAImplementation();
aInst->MethodToOverride();
delete aInst;
return 0;
}
the reasons why I'm doing this are:
I'm lazy to implement class (B) in separate files
MethodToOverride just delegates call to other class
Class B shouldn't be visible to other users
no need to worry about deleting aInst since smart pointers are used in real implementation
So my question is if I'm doing this right?
Thanks in advance!
|
You could define B in the unnamed namespace of the implementation file where you implement GetPtrToAImplementation().
A should have a virtual dtor.
By the current C++ standard, you cannot use local classes as template arguments. (Which means you can't use them with the STL, for example.)
|
2,462,951 | 2,462,985 | C++ equivalent of StringBuffer/StringBuilder? | Is there a C++ Standard Template Library class that provides efficient string concatenation functionality, similar to C#'s StringBuilder or Java's StringBuffer?
| The C++ way would be to use std::stringstream or just plain string concatenations. C++ strings are mutable so the performance considerations of concatenation are less of a concern.
with regards to formatting, you can do all the same formatting on a stream, but in a different way, similar to cout. or you can use a strongly typed functor which encapsulates this and provides a String.Format like interface e.g. boost::format
|
2,462,961 | 2,463,052 | Using static mutex in a class | I have a class that I can have many instances of. Inside it creates and initializes some members from a 3rd party library (that use some global variables) and is not thread-safe.
I thought about using static boost::mutex, that would be locked in my class constructor and destructor. Thus creating and destroying instances among my threads would be safe for the 3rd party members.
class MyClass
{
static boost::mutex mx;
// 3rd party library members
public:
MyClass();
~MyClass();
};
MyClass::MyClass()
{
boost::mutex::scoped_lock scoped_lock(mx);
// create and init 3rd party library stuff
}
MyClass::~MyClass()
{
boost::mutex::scoped_lock scoped_lock(mx);
// destroy 3rd party library stuff
}
I cannot link because I receive error:
undefined reference to `MyClass::mx`
Do I need some special initialization of such static member?
Is there anything wrong about using static mutex?
Edit: Linking problem is fixed with correct definition in cpp
boost::mutex MyClass::mx;
| You have declared, but not defined your class static mutex. Just add the line
boost::mutex MyClass::mx;
to the cpp file with the implementation of MyClass.
|
2,462,964 | 2,463,050 | When should a member function have a const qualifier and when shouldn't it? | About six years ago, a software engineer named Harri Porten wrote this article, asking the question, "When should a member function have a const qualifier and when shouldn't it?" I found it to be the best write-up I could find of the issue, which I've been wrestling with more recently and which I think is not well covered in most discussions I've found on const correctness. Since a software information-sharing site as powerful as SO didn't exist back then, I'd like to resurrect the question here.
| The article seems to cover a lot of basic ground, but the author still has a question about const and non-const overloads of functions returning pointers. Last line of the article is:
Many will probably answer "It depends." but I'd like to ask "It depends on what?"
To be absolutely precise, it depends whether the state of the A object pointee is logically part of the state of this object.
For an example where it is, vector<int>::operator[] returns a reference to an int. The int referand is "part of" the vector, although it isn't actually a data member. So the const-overload idiom applies: change an element and you've changed the vector.
For an example where it isn't, consider shared_ptr. This has the member function T * operator->() const;, because it makes logical sense to have a const smart pointer to a non-const object. The referand is not part of the smart pointer: modifying it does not change the smart pointer. So the question of whether you can "reseat" a smart pointer to refer to a different object is independent of whether or not the referand is const.
I don't think I can provide any complete guidelines to let you decide whether the pointee is logically part of the object or not. However, if modifying the pointee changes the return values or other behaviour of any member functions of this, and especially if the pointee participates in operator==, then chances are it is logically part of this object.
I would err on the side of assuming it is part (and provide overloads). Then if a situation arose where the compiler complains that I'm trying to modify the A object returned from a const object, I'd consider whether I really should be doing that or not, and if so change the design so that only the pointer-to-A is conceptually part of the object's state, not the A itself. This of course requires ensuring that modifying the A doesn't do anything that breaks the expected behaviour of this const object.
If you're publishing the interface you may have to figure this out in advance, but in practice going back from the const overloads to the const-function-returning-non-const-pointer is unlikely to break client code. Anyway, by the time you publish an interface you hopefully have used it a bit, and probably got a feel for what the state of your object really includes.
Btw, I also try to err on the side of not providing pointer/reference accessors, especially modifiable ones. That's really a separate issue (Law of Demeter and all that), but the more times you can replace:
A *getA();
const A *getA() const;
with:
A getA() const; // or const A &getA() const; to avoid a copy
void setA(const A &a);
The less times you have to worry about the issue. Of course the latter has its own limitations.
|
2,463,112 | 2,463,289 | Pointer to a C++ class member function as a global function's parameter? | I have got a problem with calling a global function, which takes a pointer to a function as a parameter.
Here is the declaration of the global function:
int lmdif ( minpack_func_mn fcn, void *p, int m, int n, double *x,
double *fvec, double ftol)
The "minpack_func_mn" symbol is a typedef for a pointer to a function, defined as:
typedef int (*minpack_func_mn)(void *p, int m, int n, const double *x,
double *fvec, int iflag );
I want to call the "lmdif" function with a pointer to a function which is a member of a class I created, and here is the declaration of this class function:
int LT_Calibrator::fcn(void *p, int m, int n, const double *x,
double *fvec,int iflag)
I am calling a global function like this:
info=lmdif(<_Calibrator::fcn, 0, m, n, x, fvec, ftol)
Unfortunately, I get a compiler error, which says:
"error C2664: 'lmdif' : cannot convert parameter 1 from 'int (__thiscall LT_Calibrator::* )(void *,int,int,const double *,double *,int)' to 'minpack_func_mn'
1> There is no context in which this conversion is possible"
Is there any way to solve that problem?
| You need a non-member or static member function; a member function pointer can't be used in place of your function type because it requires an instance to call it on.
If your function doesn't need access to a LT_Calibrator instance, then you can simply declare it static, or make it free function. Otherwise, it looks like you can use the first argument (void *p) to pass an instance pointer into a "trampoline" function, which can then call a member function. Something along the lines of this:
// member function
int LT_Calibrator::fcn(int m, ...);
// static (or non-member) trampoline
static int fcn_trampoline(void *p, int m, ...)
{
return static_cast<LT_Calibrator*>(p)->fcn(m,...);
}
info = lmdif(&fcn_trampoline, this, m, ...);
|
2,463,113 | 2,463,384 | g++ C++0x enum class Compiler Warnings | I've been refactoring my horrible mess of C++ type-safe psuedo-enums to the new C++0x type-safe enums because they're way more readable. Anyway, I use them in exported classes, so I explicitly mark them to be exported:
enum class __attribute__((visibility("default"))) MyEnum : unsigned int
{
One = 1,
Two = 2
};
Compiling this with g++ yields the following warning:
type attributes ignored after type is already defined
This seems very strange, since, as far as I know, that warning is meant to prevent actual mistakes like:
class __attribute__((visibility("default"))) MyClass { };
class __attribute__((visibility("hidden"))) MyClass;
Of course, I'm clearly not doing that, since I have only marked the visibility attributes at the definition of the enum class and I'm not re-defining or declaring it anywhere else (I can duplicate this error with a single file).
Ultimately, I can't make this bit of code actually cause a problem, save for the fact that, if I change a value and re-compile the consumer without re-compiling the shared library, the consumer passes the new values and the shared library has no idea what to do with them (although I wouldn't expect that to work in the first place).
Am I being way too pedantic? Can this be safely ignored? I suspect so, but at the same time, having this error prevents me from compiling with Werror, which makes me uncomfortable. I would really like to see this problem go away.
| You can pass the -Wno-attributes flag to turn the warning off.
(It's probably a bug in gcc?)
|
2,463,198 | 2,463,250 | printing stl containers with gdb 7.0 | I have installed GDB 7.0 and python per the following instructions. In the same manual, there is a mention of this file stl-views-1.0.3.gdb. What confuses me is where it should be placed in order to enable pretty printing of stl containers. Would someone also explain to me all of this work?
Thanks
| in the gdb:
source {full_path}stl-views-1.0.3.gdb
now you'll have new commands, such as pvector, plist, pmap and more (replace {full_path} with the full path to the file.
You can also put the command source stl-views-1.0.3.gdb in ~/.gdbinit - and then you'll have it automatically every time you launch gdb.
|
2,463,473 | 2,463,493 | Why am I getting an error converting a ‘float**’ to ‘const float**’? | I have a function that receives float** as an argument, and I tried to change it to take const float**.
The compiler (g++) didn't like it and issued :
invalid conversion from ‘float**’ to ‘const float**’
this makes no sense to me, I know (and verified) that I can pass char* to a function that takes const char*, so why not with const float**?
| See Why am I getting an error converting a Foo** → const Foo**?
Because converting Foo** → const Foo** would be invalid and dangerous ... The reason the conversion from Foo** → const Foo** is dangerous is that it would let you silently and accidentally modify a const Foo object without a cast
The reference goes on to give an example of how such an implicit conversion could allow me one to modify a const object without a cast.
|
2,463,528 | 2,463,548 | How would I use for_each to delete every value in an STL map? | Suppose I have a STL map where the values are pointers, and I want to delete them all. How would I represent the following code, but making use of std::for_each? I'm happy for solutions to use Boost.
for( stdext::hash_map<int, Foo *>::iterator ir = myMap.begin();
ir != myMap.end();
++ir )
{
delete ir->second; // delete all the (Foo *) values.
}
(I've found Boost's checked_delete, but I'm not sure how to apply that to the pair<int, Foo *> that the iterator represents).
(Also, for the purposes of this question, ignore the fact that storing raw pointers that need deleting in an STL container isn't very sensible).
Note: I have subsequently found and listed a one-line answer below... but the code is pretty awful so I've accepted GMan's saner answer.
| You have to make a function object:
struct second_deleter
{
template <typename T>
void operator()(const T& pX) const
{
delete pX.second;
}
};
std::for_each(myMap.begin(), myMap.end(), second_deleter());
If you're using boost, you could also use the lambda library:
namespace bl = boost::lambda;
std::for_each(myMap.begin(), myMap.end(), second_deleter(),
bl::bind(bl::delete_ptr(),
bl::bind(std::select2nd<myMap::value_type>(), _1));
But you might try the pointer containers library which does this automatically.
Note you are not using a map, but a hash_map. I recommend you switch to boost's unordered_map, which is more current. However, there doesn't seem to be a ptr_unordered_map.
For safety, you should wrap this thing up. For example:
template <typename T, typename Deleter>
struct wrapped_container
{
typedef T container_type;
typedef Deleter deleter_type;
wrapped_container(const T& pContainer) :
container(pContainer)
{}
~wrapped_container(void)
{
std::for_each(container.begin(), container.end(), deleter_type());
}
T container;
};
And use it like:
typedef wrapped_container<
boost::unordered_map<int, Foo*>, second_deleter> my_container;
my_container.container./* ... */
This ensures no matter what, your container will be iterated through with a deleter. (For exceptions, for example.)
Compare:
std::vector<int*> v;
v.push_back(new int);
throw "leaks!"; // nothing in vector is deleted
wrapped_container<std::vector<int*> > v;
v.container.push_back(new int);
throw "no leaks!"; // wrapped_container destructs, deletes elements
|
2,463,697 | 2,463,824 | Strange declaration(templates). C++ | How can I understand what is declared here: (this is taken from another post on this forum)
template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];
Here's how I read:
template of static function f called with (ChT<int Fallback::*, &C::x>*), but then I can't make sense why is there an address-of operator and why is there an array?
I'm still learning how to understand C++ declarations, so please explain this slowly and carefully.
| It's important to see return type.
So, return type of this function is reference to char[1];
Imagine that f returns something like reference to the following:
char ret[1];
For example
template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1]
{
static char xx[1] = {'F'};
return xx;
}
|
2,463,760 | 2,463,832 | C++ long long manipulation | Given 2 32bit ints iMSB and iLSB
int iMSB = 12345678; // Most Significant Bits of file size in Bytes
int iLSB = 87654321; // Least Significant Bits of file size in Bytes
the long long form would be...
// Always positive so use 31 bts
long long full_size = ((long long)iMSB << 31);
full_size += (long long)(iLSB);
Now..
I don't need that much precision (that exact number of bytes), so, how can I convert the file size to MiBytes to 3 decimal places and convert to a string...
tried this...
long double file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%ld", file_size_megs);
... but dosen't seem to work.
i.e. 1234567899878Bytes = 1177375.698MiB ??
| You misunderstand how the operation works. Your computation should be:
// Always use 32 bits
long long full_size = ((long long)iMSB << 32);
full_size += (unsigned long long)(iLSB);
However, the combination of 12345678, 87654321 is not 1234567887654321; it's 53024283344601009.
Then when you do
long double file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%ld", file_size_megs);
You are taking a long double (which is a floating point format) and printing it with %ld which is an integer format. What you meant was:
long long file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%lld", file_size_megs);
An alternative is to compute just the filesize in MB:
long long file_size_megs = ((long long)iMSB << (32 - 20)) + ((unsigned)iLSB >> 20);
|
2,463,855 | 2,464,092 | passing string literal to std::map::find(..) | I've got a std::map:
std::map<std::string, std::string>
I'm passing string literal to find method. Obviously, I can pass a string literal such as
.find("blah");
However, I wanted to declare it upfront, instead of hardcoding the string, so I have couple of choices now:
const std::string mystring = "blah";
const char mystring[] = "blah";
static const char * mystring = "blah";
They all work. (or at least compile). My question is, which one should I use? what's the advantage/distavantage over of the other?
| Advantages and disadvantatges:
const std::string mystring = "blah";
This is pretty much the standard C++ way to deal with strings. You can do about anything you'd ever need to do with a string with this. The main disadvantage is that it is slower. There is a dynamic allocation in there. Also, if .find relies on char[] under the scenes, you are wasting all that heap work, and it may even have to do more to get the c-usable array internally.
const char mystring[] = "blah";
This allocates your 5-byte string on the stack, so it is nice and fast. The disadvantage is that if .find uses std::string, it is going to have to do that allocation anyway, and it will do it every call instead of just once here. Also, if you ever have to do anything else with it (eg: catenate ".txt" to it), it would have been far easier to do with a std::string.
static const char * mystring = "blah";
If this is in outer scope, this means it stays local to your source file. The C++ way to do this is with unnamed namespaces instead of static though. The only advantage to doing it this way is that it is compatible with C (or at least with new enough compilers that know what "const" is).
Generally, I'd go with std::string. Except in special or extreme cases, ease of use trumps speed.
|
2,463,917 | 2,463,990 | C++: Most common way to talk to one application from the other one | In bare outlines, I've got an application which looks through the directories at startup and creates special files' index - after that it works like daemon. The other application creates such 'special' files and places them in some directory. What way of informing the first application about a new file (to index it) is the most common, simple (the first one is run-time, so it shouldn't slow it too much), and cross-platform if it is possible?
I've looked through RPC and IPC but they are too heavy (also non-cross-platform and slow (need a lot of features to work - I need a simple light well-working way), probably).
| Pipes would be one option: see Network Programming with Pipes and Remote Procedure Calls (Windows) or Creating Pipes in C (Unix).
I haven't done this in a while but from my experience with RPC, DCOM, COM, .NET Remoting, and socket programming, I think pipes is the most straightforward and efficient option.
|
2,463,944 | 2,463,993 | Is there any tool to standardize format of C++ code? | I'm looking for a tool that works on Windows to reformat some C++ code in my codebase. Essentially, I've got some code I wrote a while ago that I'd like to use, but it doesn't match the style I'm using in a more recent project.
What's the best way to reformat C++ code in a standard manner?
Billy3
| In Visual Studio: Edit / Advanced / Format Document
The format applied to the document will match the settings in: Tools / Options / Text Editor / C/C++
Visual Studio might not support all the formatting options you want applied to your document, in which case you'll need a separate tool (such as Paul Betts is suggesting) to format the way you want.
|
2,463,982 | 2,464,025 | How to pause a program for a few milliseconds? | How to pause a program for a few milliseconds using C++ managed code?
I tried Sleep() but it didn't work when I included the winbase.h file, I got lots of compile errors!
for(int i=0; i<10; i++)
{
simpleOpenGlControl1->MakeCurrent();
System::Threading::Thread::Sleep(100);
theta_rotated += 2.0* 3.141592653/(double)Model->size()/10.0;
simpleOpenGlControl1->Invalidate();
}
private: System::Void simpleOpenGlControl1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e)
{
Gl::glMatrixMode(Gl::GL_MODELVIEW);
Gl::glLoadIdentity();
Gl::glClearColor(1, 1, 1, 1);
Gl::glClear(Gl::GL_COLOR_BUFFER_BIT | Gl::GL_DEPTH_BUFFER_BIT);
camera->Tellgl();
Gl::glRotated(Angle,X,Y,Z);
RenderModels();
}
void RenderModels(void)
{
Points = gcnew System::Collections::Generic::List<Point>();
Point p(0,0) ;
int t = -5;
double r = 5;
double x, z, theta;
for(int i = 0;i < Model->size();i++)
{
theta = i*2* 3.141592653/ (double)Model->size();
x = r*sin(theta + theta_rotated);
z = r*cos(theta + theta_rotated);
Gl::glPushMatrix();
Gl::glTranslated(x,0,z);
Model->at(i).Render();
p.X=x;
p.Y=0;
Points->Add(p);
t +=1;
Gl::glPopMatrix();
}
//simpleOpenGlControl1->Invalidate();
}
| System::Threading::Thread::Sleep() as mentioned in another answer. But let me warn you, it is not precise, and for small (milliseconds) Sleep is extremely imprecise. consider that your app run together with other apps and threads and they all want processor time.
|
2,463,994 | 2,559,574 | Qt phonon video player example C++ or python | Does anyone have a working example of a video player built using Qt phonon? (in C++ )
See my related question here . I am unable to build one using Python.
| A working example of a video player built using Qt phonon: Dragon Player
And here you find the Mplayer created with Phonen too, including all the sources: Phonon MPlayer. You need to login, then you can browse the source code by clicking on "Source" and then "Browse".
EDIT: Oh, and of course the Media Player Example in the Qt Assistant, you should have a look at this, too. It plays both audio and video.
|
2,464,150 | 2,464,178 | Operator + for matrices in C++ | I suppose the naive implementation of a + operator for matrices (2D for instance)
in C++ would be:
class Matrix {
Matrix operator+ (const Matrix & other) const {
Matrix result;
// fill result with *this.data plus other.data
return result;
}
}
so we could use it like
Matrix a;
Matrix b;
Matrix c;
c = a + b;
Right?
But if matrices are big this is not efficient as we are doing one not-necessary copy (return result).
Therefore, If we wan't to be efficient we have to forget the clean call:
c = a + b;
Right?
What would you suggest / prefer ?
Thanks.
| The C++ standard gives permission for the compiler to elide the unnecessary copy in this case (it's called the "named return value optimization", usually abbreviated to NRVO). There's a matching "RVO" for when you return a temporary instead of a named variable.
Nearly all reasonably recent C++ compilers implement both NRVO and RVO, so generally speaking you can ignore the fact that this construct wouldn't otherwise be particularly efficient.
Edit: I was, of course, talking about the copy involved in returning the new matrix holding the result of the addition. You probably do want to either pass the input by const reference:
Matrix operator+(Matrix const &other) const {
Matrix result;
// ...
return result;
}
...or else, pass by value, but return the passed value:
Matrix operator+(Matrix other) const {
other += *this;
return other;
}
Note that this depends on commutativity though (i.e., it's really doing b+a instead of a+b) so while it's fine for addition, it won't work for some other operations.
|
2,464,296 | 2,464,405 | Is it possible to defer member initialization to the constructor body? | I have a class with an object as a member which doesn't have a default constructor. I'd like to initialize this member in the constructor, but it seems that in C++ I can't do that. Here is the class:
#include <boost/asio.hpp>
#include <boost/array.hpp>
using boost::asio::ip::udp;
template<class T>
class udp_sock
{
public:
udp_sock(std::string host, unsigned short port);
private:
boost::asio::io_service _io_service;
udp::socket _sock;
boost::array<T,256> _buf;
};
template<class T>
udp_sock<T>::udp_sock(std::string host = "localhost",
unsigned short port = 50000)
{
udp::resolver res(_io_service);
udp::resolver::query query(udp::v4(), host, "spec");
udp::endpoint ep = *res.resolve(query);
ep.port(port);
_sock(_io_service, ep);
}
The compiler tells me basically that it can't find a default constructor for udp::socket and by my research I understood that C++ implicitly initializes every member before calling the constructor. Is there any way to do it the way I wanted to do it, or is it too "Java-oriented" and not feasible in C++?
I worked around the problem by defining my constructor like this:
template<class T>
udp_sock<T>::udp_sock(std::string host = "localhost",
unsigned short port = 50000) : _sock(_io_service)
{
udp::resolver res(_io_service);
udp::resolver::query query(udp::v4(), host, "spec");
udp::endpoint ep = *res.resolve(query);
ep.port(port);
_sock.bind(ep);
}
So my question is more out of curiosity and to better understand OOP in C++
| When you define a constructor, you have 2 ways to "initialize" attributes:
the initializer list
the constructor body
If you do not explictly initialize one of the attributes in the initializer list, it is nonetheless initialized (by calling its default constructor) for you...
So in essence:
class Example
{
public:
Example();
private:
Bar mAttr;
};
// You write
Example::Example() {}
// The compiler understands
Example::Example(): mAttr() {}
And this of course fails if the underlying type does not have a Default Constructor.
There are various ways to defer this initialization. The "standard" way would be to use a pointer:
class Example { public: Example(); private: Bar* mAttr; };
However I prefer using Boost.Optional combined with suitable accessors:
class Example
{
public: Example();
private:
Bar& accessAttr() { return *mAttr; }
const Bar& getAttr() const { return *mAttr; }
boost::Optional<Bar> mAttr;
};
Example::Example() { mAttr = Bar(42); }
Because Boost.Optional means that there is no overhead on the allocation and no overhead on the dereferencing (the object is created in place) and yet carries the correct semantic.
|
2,464,458 | 2,465,358 | C++ thread safety - exchange data between worker and controller | I still feel a bit unsafe about the topic and hope you folks can help me -
For passing data (configuration or results) between a worker thread polling something and a controlling thread interested in the most recent data, I've ended up using more or less the following pattern repeatedly:
Mutex m;
tData * stage; // temporary, accessed concurrently
// send data, gives up ownership, receives old stage if any
tData * Send(tData * newData)
{
ScopedLock lock(m);
swap(newData, stage);
return newData;
}
// receiving thread fetches latest data here
tData * Fetch(tData * prev)
{
ScopedLock lock(m);
if (stage != 0)
{
// ... release prev
prev = stage;
stage = 0;
}
return prev; // now current
}
Note: This is not supposed to be a full producer-consumer queue, only the msot recent data is relevant. Also, I've skimmed ressource management somewhat here.
When necessary I'm using two such stages: one to send config changes to the worker, and for sending back results.
Now, my questions
assuming that ScopedLock implements a full memory barrier:
do stage and/or workerData need to be volatile?
is volatile necessary for tData members?
can I use smart pointers instead of the raw pointers - say boost::shared_ptr?
Anything else that can go wrong?
I am basically trying to avoid "volatile infection" spreading into tData, and minimize lock contention (a lock free implementation seems possible, too). However, I'm not sure if this is the easiest solution.
ScopedLock acts as a full memory barrier. Since all this is more or less platform dependent, let's say Visual C++ x86 or x64, though differences/notes for other platforms are welcome, too.
(a prelimenary "thanks but" for recommending libraries such as Intel TBB - I am trying to understand the platform issues here)
| You don't need volatile here. Use volatile only if the value can change due to something outside of your program, such as if the variable represents a memory-mapped hardware register. The values here are only modified inside your program, so you can trust the compiler to know when it can and can't cache the values.
If you need to make sure the worker and controller aren't accessing the shared data at the same time, I would recommend that you use a mutex instead. In both your Send and Fetch functions, simply lock the mutex, manipulate stage, and release the mutex. I don't know what system libraries you have available, but there's a good description of POSIX mutexes (from pthreads) here. The Win32 version (albeit with less explanation) is available here. Other libraries will use different names, but the concept is the same.
|
2,464,629 | 2,464,691 | Possible to distribute or parallel process a sequential program? | In C++, I've written a mathematical program (for diffusion limited aggregation) where each new point calculated is dependent on all of the preceding points.
Is it possible to have such a program work in a parallel or distributed manner to increase computing speed?
If so, what type of modifications to the code would I need to look into?
EDIT: My source code is available at...
http://www.bitbucket.org/damigu78/brownian-motion/downloads/
filename is DLA_full3D.cpp
I don't mind significant re-writes if that's what it would take. After all, I want to learn how to do it.
| If your algorithm is fundamentally sequential, you can't make it fundamentally not that.
What is the algorithm you are using?
EDIT: Googling "diffusion limited aggregation algorithm parallel" lead me here, with the following quote:
DLA, on the other hand, has been shown
[9,10] to belong to the class of
inherently sequential or, more
formally, P-complete problems.
Therefore, it is unlikely that DLA
clusters can be sampled in parallel in
polylog time when restricted to a
number of processors polynomial in the
system size.
So the answer to your question is "all signs point to no".
|
2,464,664 | 2,464,713 | An interview question on conditional operator | I recently encountered with this question: How to reduce this expression: s>73?61:60;.
The hint given was that Instead of using conditional operator we could use a simple comparison which will work fine.
I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself.
EDIT:The whole expression is this : s-=s>73?61:60
| Just like the other answers:
s -= (s > 73) + 60;
This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.
|
2,464,675 | 2,464,717 | How do you process a large data file with size such as 10G? | I found this open question online. How do you process a large data file with size such as 10G?
This should be an interview question. Is there a systematic way to answer this type of question?
| If you're interested you should check out Hadoop and MapReduce which are created with big (BIG) datasets in mind.
Otherwise chunking or streaming the data is a good way to reduce the size in memory.
|
2,464,826 | 2,465,576 | screenshots of covered/minimized windows | I have the following code to take screenshots of a window:
HDC WinDC;
HDC CopyDC;
HBITMAP hBitmap;
RECT rt;
GetClientRect (hwnd, &rt);
WinDC = GetDC (hwnd);
CopyDC = CreateCompatibleDC (WinDC);
hBitmap = CreateCompatibleBitmap (WinDC,
rt.right - rt.left, //width
rt.bottom - rt.top);//height
SelectObject (CopyDC, hBitmap);
//Copy the window DC to the compatible DC
BitBlt (CopyDC, //destination
0,0,
rt.right - rt.left, //width
rt.bottom - rt.top, //height
WinDC, //source
0, 0,
SRCCOPY);
ReleaseDC(hwnd, WinDC);
ReleaseDC(hwnd, CopyDC);
It is someone elses code, slightly modified, as I am not really familiar with DC and how windows draws stuff to screen.
When I have one window slightly covering another, the covering window appears on screenshots of the covered one, which is kind of inconvenient. Also, when the window is minimized, this code produces nothing much interesting.
Is there any way around this? I would imagine that taking screenshots of a minimized application would be quite difficult, but I hope that getting screenshots of covered windows is possible. Perhaps there is a different method of implementing this to get around these problems?
| No, a screenshot is exactly what it sounds like. You'll read the pixels out of the video adapter, what you get is what you see. You'll have to restore the window and bring it to the foreground to get the full view. WM_SYSCOMMAND+SC_RESTORE and SetForegroundWindow() respectively. Plus some time to allow the app to repaint its window if necessary.
The WM_PRINT message is available to ask a window to draw itself into a memory context. That could handle the overlapped window problem. But that can only work if is your window. And rarely has the expected result, programmers don't often implement WM_PRINT correctly.
|
2,464,838 | 2,466,594 | An "About" message box for a GUI with Qt | QMessageBox::about( this, "About Application",
"<h4>Application is a one-paragraph blurb</h4>\n\n"
"Copyright 1991-2003 Such-and-such. "
"For technical support, call 1234-56789 or see\n"
"<a href=\"http://www.such-and-such.com\">http://www.such-and-such.com</a>" );
This code is creating the About message box which I wanted to have with two exceptions:
1) I would like to change the icon in the message box with an aaa.png file
2) And I would like to have the link clickable. It looks like hyperlink (it is blue and underlined) but mouse click does not work
Any ideas?
| I think you should create a custom QWidget for your about widget. By this way, you can put on the widget all you want. By example, you can place QLabel using the openExternalLinks property for clickable link.
To display a custom image on the QWidget, this example may help.
|
2,465,072 | 2,465,214 | Bitmap manipulation in C++ on Windows | I have myself a handle to a bitmap, in C++, on Windows:
HBITMAP hBitmap;
On this image I want to do some Image Recognition, pattern analysis, that sort of thing. In my studies at University, I have done this in Matlab, it is quite easy to get at the individual pixels based on their position, but I have no idea how to do this in C++ under Windows - I haven't really been able to understand what I have read so far. I have seen some references to a nice looking Bitmap class that lets you setPixel() and getPixel() and that sort of thing, but I think this is with .net .
How should I go about turning my HBITMAP into something I can play with easily? I need to be able to get at the RGBA information. Are there libraries that allow me to work with the data without having to learn about DCs and BitBlt and that sort of thing?
| You can use OpenCV library as a full image processing tool.
You can also use MFC's CImage or VCL's TBitmap just to extract pixel values from HBITMAP.
|
2,465,345 | 2,465,379 | Get current time crossplatform in c++ | How can I get current time (I need hours, minutes, seconds) crossplatform in c++? I saw here make structure of values but there are a lots of another stuff that I don't need. And memory is very important here.
| The routines in <time.h> are cross-platform and in fact required to be available for conforming implementations of ISO C. Use time to retrieve the elapsed time since 1970, and localtime or gmtime to break that down into hours, minutes, and seconds, as needed.
You shouldn't be concerned that struct tm uses too much memory to store unneeded fields unless you are programming extremely memory-constrained devices, in which case you probably aren't looking for a cross-platform solution.
|
2,465,378 | 2,465,464 | How expensive is CreateThread()? | I'm just wondering exactly what factors affect how quickly createthread executes, and how long it has to live to make it "worth it".
CONTEXT: Where in my game's loops should I spawn threads?
| The main game loop is not the place to spawn worker threads. The main game loop should be as free of clutter as possible. Worker threads should be spawned during program startup and then used as need by the main game loop. Look into thread pooling techniques.
|
2,465,413 | 2,465,449 | Qt - add a hyperlink to a dialog | Is there a way to add a clickable hyperlink in a Qt Dialog? I.e. it should look like a hyperlink (blue text), and when you click on it, it should open the hyperlink in the browser. Something like that:
| Use QLabel::setOpenExternalLinks(bool), and set text on label <a href="yourlink">link text</a>.
|
2,465,512 | 2,465,566 | In C++, where are static, dynamic and local variables stored? How about in C and Java? | In C++, where are static, dynamic and local variables stored? How about in C and Java?
| If you're compiling C/C++ to create a windows executable (or maybe for any x86 system) then static and global variables are usually stored in a segment of the memory called a data segment. This memory is usually also divided to variables which are initialized and those that are not initialized by the program in their definition.
Local variables which are defined inside a functions are allocated on the running stack of the program, alongside the return address of the function.
By "dynamic" I'm assuming you mean things allocated using new or malloc. These are usually stored in yet another area of memory called "the heap" (which has nothing to do with the "heap" data structure)
All these details are highly platform dependent and usually, as a programmer you would not need to even be aware of them.
|
2,465,546 | 2,465,631 | Where do I put constant strings in C++: static class members or anonymous namespaces? | I need to define some constant strings that will be used only by one class. It looks like I have three options:
Embed the strings directly into locations where they are used.
Define them as private static constant members of the class:
//A.h
class A {
private:
static const std::string f1;
static const std::string f2;
static const std::string f3;
};
//A.cpp
const std::string f1 = "filename1";
const std::string f2 = "filename2";
const std::string f3 = "filename3";
//strings are used in this file
Define them in an anonymous namespace in the cpp file:
//A.cpp
namespace {
const std::string f1 = "filename1";
const std::string f2 = "filename2";
const std::string f3 = "filename3";
}
//strings are used in this file
Given these options, which one would you recommend and why? Thanks.
| I'd place them in anonymous namespace in the CPP file. It makes them private to the implementation and at the same moment makes it visible to the non-member functions that are part of implementation (such as operator<<).
|
2,465,708 | 2,465,755 | Is it possible to create a null function that will not produce warnings? | I have a logger in a c++ application that uses defines as follows:
#define FINEST(...) Logger::Log(FINEST, _FILE, __LINE, __func, __VA_ARGS_)
However what I would like to do is to be able to switch off these logs since they have a serious performance impact on my system. And, it's not sufficient to simply have my Logger not write to the system log. I really need to get rid of the code produced by the logs.
In order to do this, I changed the define to:
#define FINEST(...)
Which works, but this produces a whole bunch of warning in my code since variables are unused now. So what I would like to have is a sort of NULL FUNCTION that would not actually exist, but would not produce warnings for the unused variables.
So, said another way, I would like it to compile with no warnings (i.e. the compiler thinks that the variables are used for a function) but the function does not actually exist in the application (i.e. produces no performance hit).
Is this possible?
Thanks!
| You could define an empty function with unnamed parameters:
void nullFunc(int, int, int, const char*, ...) {
}
Then redefine your macro to call this function:
#define FINEST(...) nullFunc(FINEST, _FILE, __LINE, __func, __VA_ARGS_)
|
2,465,738 | 2,465,823 | C++ Long switch statement or look up with a map? | In my C++ application, I have some values that act as codes to represent other values. To translate the codes, I've been debating between using a switch statement or an stl map. The switch would look something like this:
int code;
int value;
switch(code)
{
case 1:
value = 10;
break;
case 2:
value = 15;
break;
}
The map would be an stl::map<int, int> and translation would be a simple lookup with the code used as the key value.
Which one is better/more efficient/cleaner/accepted? Why?
| Personally, I would use the map, as its use implies a data lookup - using a switch usually indicates a difference in program behavior. Furthermore modifying the data mapping is easier with a map than with a switch.
If performance is a real issue, profiling is the only way to get a usable answer. A switch may not be faster if branch mispredictions happen often enough.
Another approach to think about this is if it wouldn't make more sense to combine the code and the associated value into a datastructure, especially if the range of codes and values is static:
struct Code { int code; int value; };
Code c = ...
std::cout << "Code " << c.code << ", value " << c.value << std::end;
|
2,465,751 | 2,465,803 | How to return a 'read-only' copy of a vector | I have a class which has a private attribute vector rectVec;
class A {
private:
vector<Rect> rectVec;
};
My question is how can I return a 'read-only' copy of my Vector?
I am thinking of doing this:
class A {
public:
const vect<Rect>& getRectVec() { return rectVect; }
}
Is that the right way?
I am thinking this can guard against the callee modify the vector(add/delete Rect in vector), what about the Rect inside the vector?
| That is the right way, although you'll probably want to make the function const as well.
class A {
public:
const vect<Rect>& getRectVec() const { return rectVect; }
};
This makes it so that people can call getRectVec using a const A object.
|
2,465,845 | 5,316,835 | Eclipse CDT Error Parser for external gcc-based builder | I understand that CDT 7 will have a regular expression error parser included, but I'm using CDT 6 now.
I have an external CDT builder which just calls a shell script to trigger my build, (Jam-based). The build uses GCC, and the errors and warnings are streamed to a Console view, but of course no error parser is looking at it so nothing appears in my Problems view.
Is there a way to configure CDT to use it's GCC scanner on my console output to populate the Problems view? The GCC parser is enabled, it's just not looking at my output.
| I'm not sure if this question is still actual, but the following solution should work to populate Problems view:
1) Create an empty C++ makefile in CDT (let's call it solution1)
2) From the project's context menu (in Project Explorer) select "Import..."
3) In the "Import" wizard select "General/File System", click "Next" and select your source directory. Unfortunately CDT 6 doesn't allow to create references to files like CDT 7. Instead it will copy all sources to to the project's location in the workspace. So the top most directory which you import should contain the Jamroot. Don't forget to check all boxes for all necessary files and folders in the Import diallog.
As a more elegant alternative to Import you can just create a Folder in the eclipse project and link it to the source folder containing necessary Jamfile - thanks Vanuan for the hint.
After the files are added open project properties and do the following changes:
4) Make sure that both CDT Builder and Scanner Configuration Builder are selected on the Builders page. For CDT Builder Properties I recommend to select all options except "During Auto Build"
5) On "C/C++ Build" page uncheck "Use Default Build Command" and put in something like "${HOME}/boost.build/bin/bjam ". In "Build Location" you should put the folder with the necessary jamfile which you want to build from you project hierarchy. For example, "${workspace_loc:/solution1/Server}"
6) Switch to "Behavior" tab and add necessary bjam parameters for "Build (incremental)" and "clean" options. Uncheck "Build on resource save (Auto Build)"
7) In "C/C++ Build/Settings/Error Parsers" select all necessary parsers. Everything else should be left in default state.
After that you should be good to go.
If you have multiple projects in your source tree and you used "Import" approach, it makes sense to create a separate build configuration for each project and specify corresponding "Build Location" values for them. I use CDT 7 and since it allows to import references to source folders instead of creating physical copies I simply create a separate eclipse project in the workspace for each of the target Jamfiles. In CDT 6 it will also work if you added a linked folder instead of importing the sources.
|
2,465,964 | 2,466,932 | Are there any C++ tools that detect misuse of static_cast, dynamic_cast, and reinterpret_cast? | The answers to the following question describe the recommended usage of static_cast, dynamic_cast, and reinterpret_cast in C++:
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool like PC-Lint or Coverity Static Analysis do this?
The particular case that prompted this question was the inappropriate use of static_cast to downcast a pointer, which the compiler does not warn about. I'd like to detect this case using a tool, and not assume that developers will never make this mistake.
| Given that there is no reliable way of telling what type the pointer points to at compile time, this is a pretty hard problem to catch at compile time.
The simplest method is to do the catch at run-time, using a macro "safe_cast" which compiles to a dynamic_cast with an assert in debug, and a static_cast in release.
Now, during debugging, if the cast is inappropriate, the dynamic cast will return NULL, and assert. There is also no overhead during release.
|
2,465,983 | 2,469,249 | Devising a test strategy | As part of a new job, I have to devise and implement a complete test strategy for the company's new product. So far, all I really know about it is that it is written in C++, uses an SQL database and has a web API which is used by a browser client written using GWT.
As far as I know, there isn't much of an existing strategy, except for using Python scripts to test the web API.
I need to develop and implement a suitable strategy for unit, system, regression and release testing, preferably a fully automated one.
I'm looking for good references for:
Devising the complete test strategy.
Testing the web API.
Testing the GWT based application.
Unit testing C++ code.
In addition, any suitable tools would be appreciated.
| Testing Computer Software is a great soup-to-nuts book on the entire testing process. In addition to the items you mentioned, you'll need to think about other types of testing (performance, security, localization, stress testing, to name a few) and how to manage the test process; test plans, issue tracking, test data, test cases, in addition to the tools.
There's a lot there, and you can't do everything at once. I think a phased approach would be best, where you identify the gaps, weaknesses, and risks in the current process, prioritize them, then set up a high level plan to address them one by one.
Software QA Testing and Test Tool Resources is a good starting place for finding some tools to fit your process. StickyMinds is a nice web site dedicated to software testing, and the folks here at StackOverflow certainly know their stuff, so don't be afraid to ask.
Good luck :)
|
2,466,028 | 2,466,290 | two static libraries | I am currently providing a static library using vs2008. I am in the process of building my static library. However, since I am using another static library is there a way that i package this as a single static library. The reason here is that they will be calling functions in my library that depend on that other static library (.lib). I am not sure how to go about doing that and need some help with that.
| Here is one way:
Find out all the object files in the static library. That can be done by running the command lib STATICLIB /list
Extract each object listed. You must give the exact name from step 1 (lib STATICLIB /extract:.\debug\foo.obj)
You can then add all the objects extracted form step 2 into your library
|
2,466,131 | 2,466,156 | Is re-throwing an exception legal in a nested 'try'? | Is the following well-defined in C++, or not? I am forced to 'convert' exceptions to return codes (the API in question is used by many C users, so I need to make sure all C++ exceptions are caught & handled before control is returned to the caller).
enum ErrorCode {…};
ErrorCode dispatcher() {
try {
throw;
}
catch (std::bad_alloc&) {
return ErrorCode_OutOfMemory;
}
catch (std::logic_error&) {
return ErrorCode_LogicError;
}
catch (myownstdexcderivedclass&) {
return ErrorCode_42;
}
catch(...) {
return ErrorCode_UnknownWeWillAllDie;
}
}
ErrorCode apifunc() {
try {
// foo() might throw anything
foo();
}
catch(...) {
// dispatcher rethrows the exception and does fine-grained handling
return dispatcher();
}
return ErrorCode_Fine;
}
ErrorCode apifunc2() {
try {
// bar() might throw anything
bar();
}
catch(...) {
return dispatcher();
}
return ErrorCode_Fine;
}
I hope the sample shows my intention. My guess is that this is undefined behaviour, but I'm not sure. Please provide quotes from the standard, if applicable. Alternative approaches are appreciated as well.
Thanks!
| That's fine. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine:
§15.1/4:
The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary persists as long as there is a handler being executed for that exception.
That is:
catch(...)
{ // <--
/* ... */
} // <--
Between those arrows, you can re-throw the exception. Only when the handlers scope ends does the exception cease to exist.
Keep in mind if you call dispatch without an active exception, terminate will be called. If dispatch throws an exception in one if it's handlers, that exception will begin to propagate. More information in a related question.
|
2,466,318 | 2,590,826 | Vista Basic theme ribbon issue | Under Vista, when in Basic theme, after calling IUIFramework::Destroy() the Vista theme is lost, and enlarging the window does not display outside of the initial area.
You can repro it easily with the SimpleRibbon SDK sample. In simpleribbon.cpp, insert in the WndProc switch block:
case WM_KEYUP:
DestroyFramework();
InvalidateRect(hWnd, NULL, TRUE);
break;
Compile, run, hit a key and try to enlarge in Vista Basic Theme (no problem in Win7 or Vista aero or Windows classic).
How to work around?
[edit]
I would be satisfied with some tracks to investigate, I don't expect a cooked solution :-)
| The ribbon control seems to set a window region and forget to remove it at ribbon destruction.
Setting a null window region on return of IUIFramework::Destroy() seems to solve the problem .
|
2,466,337 | 2,467,412 | C++Builder compile issue | This is a follow-up question to this question I asked earlier. Btw thanks Neil Butterworth for your help
Issue compiling c++ in c++builder
A quick recap. I'm currently developing a C++ program for university, I used Netbeans 6.8 on my personal computer (Mac) and it all works perfect. When I try them on my windows partition or at the university PC's using C++Builder 2009 & 2010 I was getting a few compile errors which were solved by adding the following header file:
#include <string>
However now the program does compile but it doesn't run, just a blank console. And am getting the following in the compiler's event log:
Thread Start: Thread ID: 2024. Process Project1.exe (3280)
Process Start: C:\Users\Carlos\Documents\RAD Studio\Projects\Debug\Project1.exe. Base Address: $00400000. Process Project1.exe (3280)
Module Load: Project1.exe. Has Debug Info. Base Address: $00400000. Process Project1.exe (3280)
Module Load: ntdll.dll. No Debug Info. Base Address: $77E80000. Process Project1.exe (3280)
Module Load: KERNEL32.dll. No Debug Info. Base Address: $771C0000. Process Project1.exe (3280)
Module Load: KERNELBASE.dll. No Debug Info. Base Address: $75FE0000. Process Project1.exe (3280)
Module Load: cc32100.dll. No Debug Info. Base Address: $32A00000. Process Project1.exe (3280)
Module Load: USER32.dll. No Debug Info. Base Address: $77980000. Process Project1.exe (3280)
Module Load: GDI32.dll. No Debug Info. Base Address: $75F50000. Process Project1.exe (3280)
Module Load: LPK.dll. No Debug Info. Base Address: $75AB0000. Process Project1.exe (3280)
Module Load: USP10.dll. No Debug Info. Base Address: $76030000. Process Project1.exe (3280)
Module Load: msvcrt.dll. No Debug Info. Base Address: $776A0000. Process Project1.exe (3280)
Module Load: ADVAPI32.dll. No Debug Info. Base Address: $777D0000. Process Project1.exe (3280)
Module Load: SECHOST.dll. No Debug Info. Base Address: $77960000. Process Project1.exe (3280)
Module Load: RPCRT4.dll. No Debug Info. Base Address: $762F0000. Process Project1.exe (3280)
Module Load: SspiCli.dll. No Debug Info. Base Address: $759F0000. Process Project1.exe (3280)
Module Load: CRYPTBASE.dll. No Debug Info. Base Address: $759E0000. Process Project1.exe (3280)
Module Load: IMM32.dll. No Debug Info. Base Address: $763F0000. Process Project1.exe (3280)
Module Load: MSCTF.dll. No Debug Info. Base Address: $75AD0000. Process Project1.exe (3280)
I would really appreciate any help or ideas on how to solve this problem.
P.S: In the case anyone wonders why am I sticking with C++Builder is because it is the IDE professors use to evaluate our assignments.
| I am assuming that you have debugging enabled,
and you can't even step into main() with the debugger (Pressing [F7] or [F8]),
like the program is crashing before it even gets into main.
This could be a problem if you have a global (or static) instance of an object, and the object's constructor code is crashing.
If you do have a global object I.e.
MyClass object;
int main()
{ .... };
Try dynamically allocating it in main().
MyClass *object = 0;
int main()
{ object = new MyClass;
....
};
|
2,466,342 | 2,466,441 | C++ DLL creation for C# project - No functions exported | I am working on a project that requires some image processing. The front end of the program is C# (cause the guys thought it is a lot simpler to make the UI in it). However, as the image processing part needs a lot of CPU juice I am making this part in C++.
The idea is to link it to the C# project and just call a function from a DLL to make the image processing part and allow to the C# environment to process the data afterwards. Now the only problem is that it seems I am not able to make the DLL. Simply put the compiler refuses to put any function into the DLL that I compile.
Because the project requires some development time testing I have created two projects into a C++ solution. One is for the Dll and another console application. The console project holds all the files and I just include the corresponding header into my DLL project file. I thought the compiler should take out the functions that I marked as to be exported and make the DLL from them. Nevertheless this does not happens.
Here it is how I defined the function in the header:
extern "C" __declspec(dllexport) void _stdcall RobotData(BYTE* buf, int** pToNewBackgroundImage, int* pToBackgroundImage, bool InitFlag, ObjectInformation* robot1, ObjectInformation* robot2, ObjectInformation* robot3, ObjectInformation* robot4, ObjectInformation* puck);
extern "C" __declspec(dllexport) CvPoint _stdcall RefPointFinder(IplImage* imgInput, CvRect &imgROI,
CvScalar &refHSVColorLow, CvScalar &refHSVColorHi );
Followed by the implementation in the cpp file:
extern "C" __declspec(dllexport) CvPoint _stdcall RefPointFinder(IplImage* imgInput, CvRect &imgROI,&refHSVColorLow, CvScalar &refHSVColorHi ) { \\...
return cvPoint((int)( M10/M00) + imgROI.x, (int)( M01/M00 ) + imgROI.y) ;}
extern "C" __declspec(dllexport) void _stdcall RobotData(BYTE* buf, int** pToNewBackgroundImage, int* pToBackgroundImage, bool InitFlag, ObjectInformation* robot1, ObjectInformation* robot2, ObjectInformation* robot3, ObjectInformation* robot4, ObjectInformation* puck) { \\ ...};
And my main file for the DLL project looks like:
#ifdef _MANAGED
#pragma managed(push, off)
#endif
/// <summary> Include files. </summary>
#include "..\ImageProcessingDebug\ImageProcessingTest.h"
#include "..\ImageProcessingDebug\ImageProcessing.h"
BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
Needless to say it does not work. A quick look with DLL export viewer 1.36 reveals that no function is inside the library. I don't get it. What I am doing wrong ?
As side not I am using the C++ objects (and here it is the C++ DLL part) such as the vector. However, only for internal usage. These will not appear in the headers of either function as you can observe from the previous code snippets.
Any ideas? Thx,
Bernat
| It seems you are confused about which files to include in your DLL project vs your console project. If it is true that "The console project holds all the files" then this is your problem.
Your DLL project needs to include the cpp file which has the __declspec(dllexport)s. As you describe it, you have included your RefPointFinder() & RobotData() functions in the console project. In other words your DLL has no functions in it whatsoever, regardless of whether anything is exported.
Just including the .h files in the DLL main file does nothing by itself. It doesn't include these functions in the DLL.
|
2,466,486 | 2,466,549 | C++ union assignment, is there a good way to do this? | I am working on a project with a library and I must work with unions. Specifically I am working with SDL and the SDL_Event union. I need to make copies of the SDL_Events, and I could find no good information on overloading assignment operators with unions.
Provided that I can overload the assignment operator, should I manually sift through the union members and copy the pertinent members or can I simply come some members (this seems dangerous to me), or maybe just use memcpy() (this seems simple and fast, but slightly dangerous)?
If I can't overload operators what would my best options be from there? I guess I could make new copies and pass around a bunch of pointers, but in this situation I would prefer not to do that.
Any ideas welcome!
EDIT:
as requested Errors messages, and incidentally I think I have learned something...
physworld.cpp:325: error: no match for ‘operator=’ in ‘CurrentEvent = ((physworld*)this)->physworld::SDL_UserInputEvents.std::queue<_Tp, _Sequence>::pop [with _Tp = SDL_Event, _Sequence = std::deque<SDL_Event, std::allocator<SDL_Event> >]()’
/usr/include/SDL/SDL_events.h:220: note: candidates are: SDL_Event& SDL_Event::operator=(const SDL_Event&)
EDIT2:
This was so stupid... I thought that Deqeues pop() member returned the item removed. I thought the code was so simple that it couldn't directly be my code, but that turned out to be wrong.
my code looked like:
for(SDL_Event CurrentEvent; !DequeueOfSDLEvents.empty(); CurrentEvent = DequeueOfSDLEvents.pop() )
{
//Do stuff
}
So if nothing else I will learn to look more closely at member functions of containers I haven't used recently. Thanks for explaining assignment worked by default, otherwise It would have taken longer to find this.
| In a union, the elements all occupy the same memory, like they sit on top of each other. If you write to another element of a union, it overwrites the others.
As such, copying element by element is a waste of time. You could copy the largest element only, but then you would have to know which one that is (not every element of the union has to be the same size) Best thing to do is to just memcpy the union.
But its even simpler than that, you should be able to just do an assignment, and the compiler, realizing you are copying a struct or union, will do the "memcpy" for you implicitly.
|
2,466,507 | 2,466,542 | Using free function as pseudo-constructors to exploit template parameter deduction | Is it a common pattern/idiom to use free functions as pseudo-constructors to avoid having to explicitly specify template parameters?
For example, everyone knows about std::make_pair, which uses its parameters to deduce the pair types:
template <class A, class B>
std::pair<A, B> make_pair(A a, B b)
{
return std::pair<A, B>(a, b);
}
// This allows you to call make_pair(1, 2),
// instead of having to type pair<int, int>(1, 2)
// as you can't get type deduction from the constructor.
The STL also makes heavy use of this in <functional> (bind1st, not1, ptr_fun, etc...)
I find myself using this quite often, so I was just wondering if many other people use it, and if there is a name for this pattern?
| Apparently it's called "Object Generator". See "More C++ Idioms" and "Boost" on this topic.
I personally find it very useful and use it alot.
Also, I think one might see expression templates as a special form of object generators, since all they do is construct complex types by means of operand types and data you normally could specify also manually. Except, they are calling the generators implicitly
a + b + c =>
Add<Add<A, B>, C>(...)
|
2,466,622 | 2,466,657 | What is better for a student programming in C++ to learn for writing GUI: C# vs QT? | I'm a teacher(instructor) of CS in the university. The course is based on Cormen and Knuth and students program algorithms in C++. But sometimes it is good to show how an algorithm works or just a result of task through GUI. Also in my opinion it's very imporant to be able to write full programs. They will have courses concerning GUI but a three years, later, in fact, before graduatuion. I think that they should be able to write simple GUI applications earlier. So I want to teach them it.
How do you think, what is more useful for them to learn: programming GUI with QT or writing GUI in C# and calling unmanaged C++ library?
Update.
For developing C++ applications students use MS Visual studio, so C# is already installed. But QT AFAIK also can be integrated into VS.
I have following pros of C# (some were suggested there in answers):
The need to make an additional layer.
It's more work, but it forces you
explicitly specify contract between
GUI and processing data. The border between GUI and algorithms becomes very clear.
It's more popular among employers. At least, in Russia where we live. It's rather common to write performance-critical algorithms in C++ and PInvoke them from well-looking C# application/ASP.Net website. Maybe it is not so widespread in the rest of the world but in Russia Windows is very popular, especially in companies and corporations due to some reasons, so most of b2b applications are Windows applications.
Rapid development. It's much quicker
to code in .Net then in C++ due to
many reasons.
And the con is that it's a new language with own specific for students. And the mess with invoking calls to library.
| It is better to familiarize students with Qt, as Qt is actually C++. C# is a completely different beast, and if you use C#, you will very likely get your students confused about what things are Microsoft- or C#-specific vs. what is actually defined in the ISO C++ standard, whereas this will be more obvious with just C++. Moreover, Qt and C++ are portable, so your students who are using Mac OS X or Linux will thank you for choosing a cross-platform framework (Qt also works on Windows); whereas, if you use C#, you will force your students to use Windows (yes, there is Mono, but it doesn't work nearly as well as Qt does across platforms).
You might also be interested in using my C++ Project Template which provides sufficient infrastructure for devleoping a Qt GUI application in C++ using CMake, and has been tested and verified to work under Mac OS X and Ubuntu Linux (and, if I get feedback on Windows, I will ensure it works there too). The template includes code that brings up a "Hello World" GUI in Qt when run with the "--gui" commandline option.
|
2,467,000 | 2,467,184 | Is there a Java Map keySet() equivalent for C++'s std::map? | Is there a Java Map keySet() equivalent for C++'s std::map?
The Java keySet() method returns "a set view of the keys contained in this map."
| Perhaps the following might be of use:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <map>
#include <set>
#include <string>
template< class Key,
class T,
class Comparator,
class MapAllocator,
class SetAllocator>
void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map,
std::set<Key,Comparator,SetAllocator>& set)
{
set.clear();
typedef typename std::map<Key,T,Comparator,MapAllocator> map_type;
typename map_type::const_iterator itr = map.begin();
while (map.end() != itr)
{
set.insert((itr++)->first);
}
}
int main()
{
std::map<std::string, double> m;
m["one"] = 1.1;
m["two"] = 2.2;
m["three"] = 3.3;
std::set<std::string> key_set;
make_key_set(m,key_set);
std::copy(key_set.begin(), key_set.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
An overload for the make_key_set function taking STL compatible sequences such as std::vector, std::deque or std::list can be as follows:
template< class Key,
class T,
class Comparator,
class MapAllocator,
class SeqAllocator,
template<class,class> class Sequence>
void make_key_set(const std::map<Key,T,Comparator,MapAllocator>& map,
Sequence<Key,SeqAllocator>& sequence)
{
sequence.clear();
typedef typename std::map<Key,T,Comparator,MapAllocator> map_type;
typename map_type::const_iterator itr = map.begin();
while (map.end() != itr)
{
sequence.push_back((itr++)->first);
}
}
|
2,467,332 | 2,469,057 | How to debug a running C++ program in Linux? | I have a question about debugging a running C++ program in Linux. If a programming is already running and can't be interrupted, how to do that.
I can find three ways, but I don't know too much about details, I am grateful if any one can elaborate it deeper.
1) we can use GDB by specifying the process ID
gdb -p PID
In this case, what's the difference between this and attach PID?
2) We can use pstat, however, I am using Ubuntu, no pstat, but only mpstat
it seems that mpstat does not provide too much information, and not so many options.
3) check the details information under directory ./proc
In this case, just go to the directory with the PID. However, should this be done mannually?
| I can't find -p option in gdb man or their documentation, but it does work! I've tried it many times with older versions on RedHat and 7.0.1 on Debian.
I'm not sure how exactly it finds the exe by PID (maybe /proc/<PID>/exe), but it does. Since it's not described in their documentation, perhaps it not the most recommended way, but I haven't had any problems with it.
There's no noticeable difference between gdb -p <PID> and running gdb and in the their shell typing attach <PID>.
I personally prefer ps xa| grep myprogram for getting the PID
|
2,467,336 | 2,467,496 | What is a good CPU/PC setup to speed up intensive C++/templates compilation? | I currently have a machine with an Opteron 275 (2.2Ghz), which is a dual core CPU, and 4GB of RAM, along with a very fast hard drive. I find that when compiling even somewhat simple projects that use C++ templates (think boost, etc.), my compile times can take quite a while (minutes for small things, much longer for bigger projects). Unfortunately only one of the cores is pegged at 100%, so I know it's not the I/O, and it would seem that there is no way to take advantage of the other core for C++ compilation?
| Compile time problems with templates are often link problems, rather than compilation problems.
Using templates internally in your .cpp files, but making sure that the headers don't actually include the template, is a good way to fix those. That can be done by either forward declaring the class, or wrapping your implementation class in an abstract base class that just declares the public members (the Pimpl Idiom, basically).
|
2,467,353 | 2,467,373 | Memory efficient way to remove duplicate lines in a text file using C++ | What is the most memory efficient way to remove duplicate lines in a large text file using C++?
Let me clarify, I'm not asking for code, just the best method. The duplicate lines are not guaranteed to be adjacent. I realize that an approach optimized for minimal memory usage would result in slower speeds however this is my restriction as the files are far too large.
| i would hash each line and then seek back to lines that have non-unique hashes and compare them individually (or in a buffered fashion). this would work well on files with a relatively low occurence of duplicates.
When you use a hash, you can set the memory used to a constant amount (i.e., you could have a tiny hash table with just 256 slots or something larger. in any case, the amount of mem can be restricted to any constant amount.) the values in the table are the offset of the lines with that hash. so you only need line_count*sizeof(int) plus a constant to maintain the hash table.
even simpler (but much slower) would be to scan the entire file for each line. but i prefer the first option. this is the most memory efficient option possible. you would only need to store 2 offsets and 2 bytes to do the comparison.
|
2,467,384 | 2,467,411 | What type can hold member-function-pointers of difference classes in C++? | I need an array to hold member-function-pointers of different classes. How can I define the array?
The code should look like this:
arr[0] = &CMyClass::FuncX;
arr[1] = &CYourClass::FuncY;
arr[2] = &CHerClass::FuncZ;
I tried void*, but it doesn't work.
| You can't; they are all different types and arrays are homogeneous.
Regardless what the arguments are or what the return value is, there is an implicit this which is unique to the class type. The type of a class member pointer is:
return_value (class_type::*)(parameters);
As you can see, because they belong to different classes they will always be a different type. Even if it were the same class, the return_value and parameters would have to be consistent to create an array, otherwise you'd still have different types.
What's the bigger picture? Boost.Bind with Boost.Function comes to mind. Also, virtual functions may solve your problem.
|
2,467,413 | 2,467,426 | Sort CMap Key by String Length | Previously, I am using STL map to perform the mentioned task.
struct ltstr
{
bool operator()(std::string s1, std::string s2) const
{
const int l1 = s1.length();
const int l2 = s2.length();
if (l1 == l2) {
// In alphabetical order.
return s1.compare(s2) < 0;
}
// From longest length to shortest length.
return l1 > l2;
}
};
std::map<std::string, int, ltstr> m;
How can I perform the same task using CMap?
// How to make key sorted by string length?
CMap<CString, LPCTSTR, int, int> m;
| You cannot. From the MSDN documentation for CMap:
You might think that this iteration is sequential by key value; it is not. The sequence of retrieved elements is indeterminate.
|
2,467,568 | 2,467,626 | How can I change the precision of printing with the stl? | I want to print numbers to a file using the stl with the number of decimal places, rather than overall precision.
So, if I do this:
int precision = 16;
std::vector<double> thePoint(3);
thePoint[0] = 86.3671436;
thePoint[1] = -334.8866574;
thePoint[2] = 24.2814;
ofstream file1(tempFileName, ios::trunc);
file1 << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
I'll get numbers like this:
86.36714359999999\-334.8866574\24.28140258789063
What I want is this:
86.37\-334.89\24.28
In other words, truncating at two decimal points. If I set precision to be 4, then I'll get
86.37\-334.9\24.28
ie, the second number is improperly truncated.
I do not want to have to manipulate each number explicitly to get the truncation, especially because I seem to be getting the occasional 9 repeating or 0000000001 or something like that that's left behind.
I'm sure there's something obvious, like using the printf(%.2f) or something like that, but I'm unsure how to mix that with the stl << and ofstream.
| Use std::fixed , this should work for you.
file1 << std::fixed << std::setprecision(precision)
<< thePoint[0] << "\\"
<< thePoint[1] << "\\"
<< thePoint[2] << "\\";
|
2,467,608 | 2,474,374 | TeeChart VCL vs .NET | Is TeeChart .NET built from the same source as TeeChart VCL? I'm just wandering as we have a VCL application heavily dependent on TeeChart and I would like to redevelop the GUI component in .NET so I can switch from the Codegear IDE to Visual Studio.
| The .NET Framework and VCL are two very, very different libraries. The different versions of TeeChart would not be built on the same source, although they likely will have very similar APIs.
|
2,467,625 | 2,467,683 | How can I eliminate an element in a vector if a condition is met | I have a vector of Rect: vector<Rect> myRecVec;
I would like to remove the ones which are overlapping in the vector:
So I have 2 nested loop like this:
vector<Rect>::iterator iter1 = myRecVec.begin();
vector<Rect>::iterator iter2 = myRecVec.begin();
while( iter1 != myRecVec.end() ) {
Rectangle r1 = *iter1;
while( iter2 != myRecVec.end() ) {
Rectangle r2 = *iter1;
if (r1 != r2) {
if (r1.intersects(r2)) {
// remove r2 from myRectVec
}
}
}
}
My question is how can I remove r2 from the myRectVect without screwing up both my iterators? Since I am iterating a vector and modifying the vector at the same time?
I have thought about putting r2 in a temp rectVect and then remove them from the rectVect later (after the iteration). But how can I skip the ones in this temp rectVect during iteration?
|
You need to increment iter1 and iter2.
erase returns an iterator to the next element. When you delete, use this instead of incrementing the iterator.
Like so:
while( iter1 != myRecVec.end() ) {
Rectangle r1 = *iter1;
iter2 = iter1 + 1;
while( iter2 != myRecVec.end() ) {
Rectangle r2 = *iter2;
if( r1.intersects(r2) ) {
iter2 = myRectVec.erase(iter2);
}
else {
++iter2;
}
++iter1;
}
|
2,467,690 | 2,467,692 | Is there any c++ class that can't be used in STL? | Just come up with this question. Any hint?
| classes that can't be copied. STL containers require objects to be copyable since the container owns a copy of that object, and needs to be able to move it around.
|
2,467,807 | 2,467,826 | C/C++ for Core Logic Development of a Web Application? | Can C/C++ be choice of keeping all your logic (business/domain) for web application?
Why?
I've two resources (cousins) having knowledge on C/C++ and me also good in C/C++, Python, HTML, CSS and JavaScript.
We like to utilize our free time to work on our some good ideas we developed together. The ideas require knowledge of web application development. And I'm the only one who has it.
Is there a way they developed the core in C/C++ and I do the rest of scripting for front-end development?
Thanks.
| C/C++ and Python can be integrated fairly easily, but Python really should be a snap for anyone that knows C well to pick up in a week.
|
2,468,122 | 2,468,139 | Why can't a std::vector take a local type? | void foo() {
struct Foo { .. };
std::vector<Foo> vec; // why is this illegal?
}
I'm not returning Foo to the outside world. It's just a temporary type that I use within the function.
| A local class can't be a template argument. Because the standard says:-
14.3.1 paragraph 2:
"A local type, a type with no linkage, an unnamed type or a type
compounded from any of these types shall not be used as a
template argument for a template type parameter."
[Example:
template <class T> class X { /* ... */ };
void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as templateargument
X<S*> x4; // error: pointer to local type used as templateargument
}
-end example] [Note: a template type argument may be an incomplete
type (3.9). ]"
One workaround is suggested here on c.l.c++.moderated.
UPDATE:
There was some discussion on why is it not possible to have local-classes as template arguments? The links here and here on c.std.c++ discuss the same.
|
2,468,152 | 2,468,168 | Size of a class with 'this' pointer | The size of a class with no data members is returned as 1 byte, even though there is an implicit 'this' pointer declared. Shouldn't the size returned be 4 bytes(on a 32 bit machine)? I came across articles which indicated that 'this' pointer is not counted for calculating the size of the object. But I am unable to understand the reason for this.
Also, if any member function is declared virtual, the size of the class is now returned as 4 bytes. This means that the vptr is counted for calculating the size of the object. Why is the vptr considered and 'this' pointer ignored for calculating the size of object?
| The this pointer is not a member of the class. It's just a construct that is used in methods belonging to the class to refer to the current instance.
If you have a class like this:
class IntPair
{
public:
IntPair(int a, int b) : _a(a), _b(b) { }
int sum() const { return _a + _b; }
public:
int _a;
int _b;
};
This class only needs space for two instances of int for each instance. Once you've created an instance and are running the sum() method, that method is called with a pointer to the instance, but that pointer always comes from somewhere else, it isn't stored in the object instance.
For example:
IntPair *fib12 = new IntPair(89, 144);
cout << fib12->sum();
Notice how the variable that becomes the this pointer is stored outside the object, in the scope that created it.
You could, in fact, always transform a method like the one above into:
static int sum2(const IntPair* instance)
{
return instance->_a + instance->_b;
}
If the above is defined inside the class (so it can access the private members), there's no difference. In fact, this is how methods are implemented behind the scene; the this pointer is just a hidden argument to all member methods.
The call would become:
IntPair* fib12 = new IntPair(89, 144);
cout << IntPair::sum2(fib12);
|
2,468,161 | 2,496,393 | How to reliably replace a library-defined error handler with my own? | On certain error cases ATL invokes AtlThrow() which is implemented as ATL::AtlThrowImpl() which in turn throws CAtlException. The latter is not very good - CAtlException is not even derived from std::exception and also we use our own exceptions hierarchy and now we will have to catch CAtlException separately here and there which is lots of extra code and error-prone.
Looks like it is possible to replace ATL::AtlThrowImpl() with my own handler - define _ATL_CUSTOM_THROW and define AtlThrow() to be the custom handler before including atlbase.h - and ATL will call the custom handler.
Not so easy. Some of ATL code is not in sources - it comes compiled as a library - either static or dynamic. We use the static - atls.lib. And... it is compiled in such way that it has ATL::ThrowImpl() inside and some code calling it. I used a static analysis tool - it clearly shows that there're paths on which the old default handler is called.
To ensure I even tried to "reimplement" ATL::AtlThrowImpl() in my code. Now the linker says it sees two declarations of ATL::AtlThrowImpl() which I suppose confirms that there's another implementation that can be called by some code.
How can I handle this? How do I replace the default handler completely and ensure that the default handler is never called?
| I encountered similar problems when writing my own memory manager and wanted to overrule malloc and free.
The problem is that ATL::AtlThrowImpl is probably part of a source file that also includes other files that are really needed.
If the linker sees a reference to a function in one of the object files, it pulls in the object file with that function, including all other functions in that same object file.
The solution is to look up in the ATL sources where ATL::AtlThrowImpl is defined and see if the source contains other functions. You will also need to implement the other functions to prevent the linker from having any reference to the original ATL source.
|
2,468,203 | 2,468,254 | How can I make `new[]` default-initialize the array of primitive types? | Every now and then I need to call new[] for built-in types (usually char). The result is an array with uninitialized values and I have to use memset() or std::fill() to initialize the elements.
How do I make new[] default-initialize the elements?
| int* p = new int[10]() should do.
However, as Michael points out, using std::vector would be better.
|
2,468,367 | 2,468,538 | Is new int[10]() valid c++? | While trying to answer this question I found that the code int* p = new int[10](); compiles fine with VC9 compiler and initializes the integers to 0. So my questions are:
First of all is this valid C++ or is
it a microsoft extension?
Is it guaranteed to initialize all
the elements of the array?
Also, is there any difference if I
do new int; or new int();? Does
the latter guarantee to initialize
the variable?
| First of all is this valid C++ or is it a microsoft extension?
It is valid in C++, the relevant part of the standard is 5.3.4, with the first paragraph containing the grammar
Is it guaranteed to initialize all the elements of the array?
Yes. Paragraph 5.3.4/15 states that
A new-expression that creates an object of type T initializes that object as follows:
...
If the new-initializer is of the form (), the item is value-initialized (8.5)
where value initialized for POD means zero-initialize.
Also, is there any difference if I do new int; or new int();? Does the latter guarantee to initialize the variable?
Yes they are different. According with the quote above new int() will zero-initialize the integer. In a previous block of the same paragraph:
If the new-initializer is omitted:
If T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-initialized (8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor.
Otherwise, the object created has indeterminate value. If T is a const-qualified type, or a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed;
so new int will not initialize the memory.
|
2,468,792 | 2,621,627 | Flushing a boost::iostreams::zlib_compressor. How to obtain a "sync flush"? | Is there some magic required to obtain a "zlib sync flush" when using boost::iostreams::zlib_compressor ? Just invoking flush on the filter, or strict_sync on a filtering_ostream containing it doesn't see to do the job (ie I want the compressor to flush enough that the decompressor can recover all the bytes consumed by the compressor so far, without closing the stream).
Looking at the header, there seem to be some "flush codes" defined (notably a sync_flush) but it's unclear to me how they should be used (bearing in mind my compressor is just added into a filtering_ostream).
| It turns out there is a fundamental problem that the symmetric_filter that
zlib_compressor inherits from isn't itself flushable (which seems rather
an oversight).
Possibly adding such support to symmetric_filter would be as simple as adding the flushable_tag and exposing the existing private flush methods, but for now I can live with it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.