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
|
|---|---|---|---|---|
540,140
| 540,159
|
What is the conventions for headers and cpp files in C++?
|
In C++, what is the convention for including headers for class files in the "main" file. e.g.
myclass.h
class MyClass {
doSomething();
}
myclass.cpp
doSomething() {
cout << "doing something";
}
run.cpp
#include "myclass.h"
#include "myclass.cpp"
etc..
Is this relatively standard?
|
You don't include the .cpp file, only the .h file. The function definitions in the .cpp will be compiled to .obj files, which will then be linked into the final binary. If you include the .cpp file in other .cpp files, you will get two different .obj files with the same funciton definition compiled, which will lead to linker error.
|
540,252
| 540,500
|
Can any IDE or framework help test new code quickly without having to run the whole application
|
I mainly develop in native C++ on Windows using Visual Studio.
A lot of times, I find myself creating a new function/class or whatever, and I just want to test that piece of logic I just wrote, quickly.
A lot of times, I have to run the entire application, which sometimes could take a while since there are many connected parts.
Is there some sort of tool that will allow me to test that new piece of code quickly without having to run the whole application?
i.e.
Say I have a project with about 1000 files, and I'm adding a new class called Adder. Adder has a method Add( int, int );
I just want the IDE/tool to allow me to test just the Adder class (without me having to create a new project and write a dummy main.cpp) by allowing me to specify the value of the inputs going into Adder object. Likewise, it would be nice if it would allow me to specify the expected output from the tested object.
What would be even cooler is if the IDE/tool would then "record" these sets of inputs/expected output, and automatically create unit tester class based on them. If I added more input/output sets, it would keep building a history of input/outputs.
Or how about this: what if I started the actual application, feed some real data to it, and have the IDE/tool capture the complete inputs going into the unit being tested. That way, I can quickly restart my testing if I found some bugs in my program or I want to change its interface a bit. I think this feature would be so neat, and can help developer quickly test / modify their code.
Am I talking about mock object / unit testing that already exists?
Sidenote: it would be cool if Visual Studio debugger has a "replay" technology where user can step back to find what went wrong. Such debugger already exists here: http://www.totalviewtech.com/
|
It's very easy to get started with static unit testing in C++ - three lines of code.
VS is a bit poor in that you have to go through wizards to make a project to build and run the tests, so if you have a thousand classes you'd need a thousand projects. So for large projects on VS I've tended to organised the project into a few DLLs for independent building and testing rather than monolithic ones.
An alternative to static tests more similar to your 'poke and dribble' script could be done in python, using swig to bind your code to the interpreter, and python's doc tests . I haven't used both together myself. Again, you'd need a separate target to build the python binding, and another to run the tests, rather than it being just a simple 'run this class' button.
|
540,337
| 540,357
|
How to Overcome Errors Thrown by mmsystem.h
|
I am not able to get out of these simple bugs, but would be great full if some one could answer to weed out from these errors. I included windows.h and some other necessary headers but couldn't able get out of it.
Snippet of errors:
error C2146: syntax error : missing ';' before identifier 'MMVERSION'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C2143: syntax error : missing ';' before '*'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C2146: syntax error : missing ';' before identifier 'ms'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Thanks In Advance
|
Look in mmsystem.h, lines 112 and 113:
#ifdef _WIN32
typedef UINT MMVERSION; /* major (high byte), minor (low byte) */
So be sure to include windows.h befor including mmsystem.h, and if it does not help, try #defineing _WIN32 manually.
|
540,515
| 540,624
|
Named constructor and inheritance
|
I'm working on C++ framework and would like to apply automatic memory management to a number of core classes. So far, I have the standard approach which is
class Foo
{
public:
static
shared_ptr<Foo> init()
{
return shared_ptr<Foo>(new Foo);
}
~Foo()
{
}
protected:
Foo()
{
}
};
// Example of use
shared_ptr<Foo> f = Foo::init();
However, the above breaks when I subclass Foo, since even tho init() is inherited, it still returns shared_ptr<Foo> which contains a pointer to instance of Foo.
Can anyone think of an elegant solution to this? Should I perhaps just stick with (semi-)manually wrapping instances of class with shared_ptr? This would also give ability to expose parameterized constructors without declaring new named constructors...
Ie.
template <typename T>
shared_ptr<T> make_shared(T* ptr)
{
return shared_ptr<T>(ptr)
}
// Example
shared_ptr<T>
f1 = make_shared(new Foo()),
f2 = make_shared(new Foo(1,2));
|
I don't understand what this achieves, you don't appear to be getting any extra memory management using this init function than by simply declaring a shared_ptr.
int main( void )
{
shared_ptr<foo> a = foo::init();
shared_ptr<foo> b( new foo );
}
What's the difference. shared_ptr provides the memory management, not anything in init.
|
540,666
| 540,682
|
Will the ".target-name" targets in make files always run?
|
I'm new to make and makefiles, so forgive me if this is very basic.
I'm looking through some makefiles in my project and I'm seeing 2 types of targets -- targets that don't begin with a . character and targets that do.
And from what I'm guessing, it seems like the ".target-name" targets are always executed, is my assumption true? I did read about makefiles by Googling but didn't find anything specific to this.
And as always, thanks for the answers!
|
No.
The targets with a dot are normally special meaning targets (i.e. their functioniality is builtin into make). One of them is
.PHONY, this is the one that defines the targets which are always executed (that means, the commands in their rules are run unconditionally).
But there are also others, like .DEFAULT for the default rule, or .PRECIOUS with does not delete implicit built targets when interrupted.
|
540,721
| 544,287
|
compile directly from vim
|
I'd like to compile cpp file w/o turning off vi.
I know the :!g++ file.cpp but I prefer :make so I added this line in .vimrc file
au FileType C set makeprg=gcc\ %
au FileType Cpp set makeprg=g++\ %
but I keep getting
"make: ***** No targets specified and no makefile found. Stop.** "message.
can anyone tell me what is wrong with my setting?
I use to compile successfully with the option above.
|
I should change C,Cpp into c,cpp, then it works fine.
thank you all, especially Rob Wells, your answer helped me a lot. thank you.
|
540,748
| 540,850
|
void, VOID, C and C++
|
I have the following code:
typedef void VOID;
int f(void);
int g(VOID);
which compiles just fine in C (using gcc 4.3.2 on Fedora 10). The same code compiled as C++ gives me the following error:
void.c:3: error: ‘<anonymous>’ has incomplete type
void.c:3: error: invalid use of ‘VOID’
Now, this is something in external library and I would like the owner to fix that problem. So I have a question - does C++ standard forbids this construct? Could you give me a pointer/citation? The only thing I can recall is that function declaration with (void) to signal empty parameter list is deprecated in C++, but I don't understand why typedefed VOID does not work.
|
Yes, as far as i know the second declaration is invalid in C++ and C89, but it is valid in C99.
From The C99 draft, TC2 (6.7.5.3/10):
The special case of an unnamed parameter of type void as the only item in the list
specifies that the function has no parameters.
It's explicitly talking about the type "void", not the keyword.
From The C++ Standard, 8.3.5/2:
If the parameter-declaration-clause is empty, the function takes no arguments. The parameter list (void) is equivalent to the empty parameter list.
That it means the actual keyword with "void", and not the general type "void" can also be seen from one of the cases where template argument deduction fails (14.8.2/2):
Attempting to create a function type in which a parameter has a type of void.
It's put clear by others, notable in one core language issue report here and some GCC bugreports linked to by other answers.
To recap, your GCC is right but earlier GCC versions were wrong. Thus that code might have been successfully compiled with it earlier. You should fix your code, so that it uses "void" for both functions, then it will compile also with other compilers (comeau also rejects the second declaration with that "VOID").
|
540,800
| 540,836
|
Runtime dependency for std::string concatenation
|
std::string sAttr("");
sAttr = sAttr+VAL_TAG_OPEN+sVal->c_str()+VAL_TAG_CLOSE;
else where in the code I have defined
const char VAL_TAG_OPEN[] = "<value>";
sVal is a variable that is retrieved off of a array of string pointers. This works fine in most of the system, windows and linux. However at a customer site, where to my belief has a version of linux on which we had done some extensive testing, produce a result as if I have never used the VAL_TAG_OPEN and VAL_TAG_CLOSE. The results I recieve is for
sAttr = sAttr+sVal->c_str();
Whats going on ?. Does std::string concatenation varies across runtime ?
|
Why the ->c_str()? If sVal is a std::string, try removing this call. Remember that the order of evaluation is undefined, so you may end up adding pointers instead of concatenating strings, because VAL_TAG_OPEN, sVal->c_str() and VAL_TAG_CLOSE are all plain C strings. I suggest you use the addition assignment operator +=, e.g. :
sAttr += VAL_TAG_OPEN;
sAttr += *sVal; /* sVal->c_str() ? */
sAttr += VAL_TAG_CLOSE;
(which should be faster anyway).
|
540,822
| 540,864
|
Allocating memory for triple pointer
|
The function somefunction() takes a triple pointer as an argument.
int somefunction(tchar ***returnErrors);
How to allocate memory for the returnErrors parameter?
|
At a guess . . .
You can think of returnErrors as a pointer to an array of strings.
The first * imples pointer to array
of tchar (or a single string of
tchars)
The second * imples a pointer to an
array of strings.
The last * is so you can change
returnErrors and pass back the new
memory.
To delare memory for this (silly example, allocating memory inside SomeFunction)
tchar ** errors;
// Oops it appears I need to pass back two error strings (+ 1 for null on end, so we know there are no more - thanks tlholaday)
errors = malloc(sizeof(tchar*) * 3);
// the first string has length 20 (+ 1 for null terminator)
errors[0] = malloc(sizeof(tchar) * 21);
// the second string has length 30 (+ 1 for null terminator)
errors[1] = malloc(sizeof(tchar) * 31);
// ensure the last is null
errors[2] = 0;
*returnErrors = errors;
NB: The calling function needs to know that SomeFunction has allocated memory and needs to free it.
|
540,920
| 540,946
|
Which version of safe_delete is better?
|
#define SAFE_DELETE(a) if( (a) != NULL ) delete (a); (a) = NULL;
OR
template<typename T> void safe_delete(T*& a) {
delete a;
a = NULL;
}
or any other better way
|
Clearly the function, for a simple reason. The macro evaluates its argument multiple times. This can have evil side effects. Also the function can be scoped. Nothing better than that :)
|
541,022
| 541,048
|
Stringstream extract integer
|
Why do I fail to extract an integer value into the Num variable?
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
string Digits("1 2 3");
stringstream ss(Digits);
string Temp;
vector<string>Tokens;
while(ss >> Temp)
Tokens.push_back(Temp);
ss.str(Tokens[0]);
int Num = 0;
ss >> Num;
cout << Num; //output: 0
}
|
When the stream extracts the last of the 3 digist "1 2 3" the eof state will be set. This is not cleared by the str() member,you need to do it yourself. Change your code to:
ss.clear();
ss.str(Tokens[0]);
|
541,062
| 541,097
|
boost::asio::serial_port reading after reconnecting Device
|
I have a problem with the boost::asio::serial_port class reading from a GPS device (USB-Serial). Connecting the device and reading from it works fine, but when I disconnect and reconnect the device, read_some doesn't read any bytes from the port.
As boost doesn't seam to detect that the serial port is gone ( is_open() returns true ), I periodically cancel(), close() and open( GPS_PORT ) the device when I don't get data, resetting the port options on the way. But this doesn't help either, the input buffer stays empty.
Am I missing something, or doing something wrong, or is this a bug in asio? Is there a standard way to detect that the port is gone?
|
It's hard to say what is the exact reason in your case, but practice shows that you often need to disable RTS sensitivity on your serial port.
RTS is a pin on real RS-232 interface that is on when a device on the other side is on.
serial_port::read_some invokes underlying Windows API function that looks on this signal.
As you don't have the real RS-323 device, you need to rely on the driver emulation of this signal which may be faulty (and unfortunately often is).
To disable it, invoke serial_port::set_option(DCB) with RTSControl set to RTS_CONTROL_DISABLE.
If close()'ing your handle doesn't help, it may be a problem with boost. Source code for close() looks like this:
boost::system::error_code close(implementation_type& impl,
boost::system::error_code& ec)
{
if (is_open(impl))
{
if (!::CloseHandle(impl.handle_))
{
DWORD last_error = ::GetLastError();
ec = boost::system::error_code(last_error,
boost::asio::error::get_system_category());
return ec;
}
impl.handle_ = INVALID_HANDLE_VALUE;
impl.safe_cancellation_thread_id_ = 0;
}
ec = boost::system::error_code();
return ec;
}
, i. e. if CloseHandle() fails for some reason (or hangs), the internal handle value is not beign assigned to INVALID_HANDLE_VALUE and is_open() will always return true.
To work around this, check is_open() right after close()'ing, and if it returns true, destroy whole instance of boost::asio::serial_port and create it again.
|
541,078
| 541,091
|
Catching c++ base exceptions
|
In my project we have a base exception. For handling showing error dialogs, log and such.
Im looking for a way to handle all derived classes of that exception, I thought this would work:
try
{
main_loop();
}
catch (const MyExceptionBase* e)
{
handle_error(e);
}
As every child instance thrown could be represented by a pointer to its parent. But no, when exceptions are thrown now, its an unhandled exception.
Why is this? Do c++ only throw exceptions as references? Thereby rendering my catch block useless? But then why does this even compile in the first place?
The only other way I can think of is this:
try
{
main_loop();
}
catch (const ExceptionA& e)
{
handle_error(e);
}
catch (const ExceptionB& e)
{
handle_error(e);
}
catch (const ExceptionC& e)
{
handle_error(e);
}
Which seems kinda ugly. What is the correct way to do this? Dont have a base exception class? Or can it be solved in the way I want?
Ps: What handle_error() does is simply make use of the base class function display_message_box() and cleanly shutdown the program.
|
Just mix the two approaches: use the base class, and use a reference.
try
{
main_loop();
}
catch (const MyExceptionBase& e)
{
handle_error(e);
}
BTW C++ can catch pointers, if you throw them. It's not advisable though.
|
541,386
| 546,390
|
Why do profilers need administrative privs (on Windows)
|
I've been evaluating profilers and memory checking tools for native C++ programs on Windows and all of them want to be installed and run with administrator privileges. I rarely log in as admin on my machine. If I need to install something or do something that requires administrative privileges, I use runas and it works pretty well.
Is it legitimate for a profiler to require admin privileges, or are the profiler developers just being lazy? Am I being unreasonable by rejecting all of these tools on this basis?
I'm developing with VS 2005 on an XP Pro machine.
|
I've been reading about this and I'm slowly coming to the conclusion that profiler-like tools in general do not require administrative access, but stating that you require it is an easy way for the tool makers to avoid all problems related to insufficient privileges.
So, I guess they are being lazy but also somewhat pragmatic.
Correct me if I'm wrong (I'm no expert on the Windows security model), but I believe one way to handle this situation would be to require admin privileges only at install time. Then create a ProfilerUsers user group and grant any necessary privileges to that group, then ask which computer users should be added to that group.
The most shocking thing I've discovered is that a lot of developers run all the time with administrative privileges.
|
541,561
| 541,862
|
Using Boost Tokenizer escaped_list_separator with different parameters
|
Hello i been trying to get a tokenizer to work using the boost library tokenizer class.
I found this tutorial on the boost documentation:
http://www.boost.org/doc/libs/1 _36 _0/libs/tokenizer/escaped _list _separator.htm
problem is i cant get the argument's to escaped _list _separator("","","");
but if i modify the boost/tokenizer.hpp file it work's.
but that's not and ideal solution was wondering if there's anything i am missing to get diferent arguments into the escaped _list _separator.
i want to make it split on spaces with " and ' for escaping and with no escape character inside the quoted string.
this is used for a argument parsing system in a ingame console system.
include <iostream>
include <boost/tokenizer.hpp>
include <string>
int main()
{
using namespace std;
using namespace boost;
string s = "exec script1 \"script argument number one\"";
string separator1("");//dont let quoted arguments escape themselves
string separator2(" ");//split on spaces
string separator3("\"\'");//let it have quoted arguments
tokenizer<escaped_list_separator<char>(separator1,separator2,separator3)> tok(s);
for(tokenizer<escaped_list_separator<char>(separator1,separator2,separator3)>::iterator beg=tok.begin(); beg!=tok.end();++beg)
{
cout << *beg << "\n";
}
}
the error from visual studio 2005 is
error C2974: 'boost::tokenizer' : invalid template argument for 'TokenizerFunc', type expected
EDIT:
This question was awnsered by ferrucio and explained by peter thank's everybody.
|
try this:
#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
int main()
{
using namespace std;
using namespace boost;
string s = "exec script1 \"script argument number one\"";
string separator1("");//dont let quoted arguments escape themselves
string separator2(" ");//split on spaces
string separator3("\"\'");//let it have quoted arguments
escaped_list_separator<char> els(separator1,separator2,separator3);
tokenizer<escaped_list_separator<char>> tok(s, els);
for(tokenizer<escaped_list_separator<char>>::iterator beg=tok.begin(); beg!=tok.end();++beg)
{
cout << *beg << "\n";
}
}
|
542,006
| 542,499
|
Replace C style comments by C++ style comments
|
How can I automatically replace all C style comments (/* comment */) by C++ style comments (// comment)?
This has to be done automatically in several files. Any solution is okay, as long as it works.
|
This tool does the job:
https://github.com/cenit/jburkardt/tree/master/recomment
RECOMMENT is a C++ program which
converts C style comments to C++ style
comments.
It also handles all the non-trivial cases mentioned by other people:
This code incorporates suggestions and
coding provided on 28 April 2005 by
Steven Martin of JDS Uniphase,
Melbourne Florida. These suggestions
allow the program to ignore the
internal contents of strings, (which
might otherwise seem to begin or end
comments), to handle lines of code
with trailing comments, and to handle
comments with trailing bits of code.
|
542,028
| 542,118
|
Does the termination condition of a 'for loop' refresh in VC++ 6?
|
for (int i = 0 ; i < stlVector.size() ; i++)
{
if (i == 10)
{
stlVector.erase(stlVector.begin() + 5 )
}
}
Does the termination condition part "stlVector.size()" take "stlVector.erase(...)"
into consideration? In other word does stlVector.size() refresh for every loop iteration?
I can't test it right now, so i posted a question here.
Thx in advance!
Best regards,
zhengtonic
|
Just to be clear, don't think of it in terms of the loop refreshing anything. Every time the condition is checked (at the start of each time through the loop), the size() method is called on the stlVector variable, and the current size of the vector is returned.
The erase() method reduces the size of the vector, so the next time size() is called, the returned value will be smaller.
|
543,306
| 543,367
|
Platform-independent GUID generation in C++?
|
What is the best way to programmatically generate a GUID or UUID in C++ without relying on a platform-specific tool? I am trying to make unique identifiers for objects in a simulation, but can't rely on Microsoft's implementation as the project is cross-platform.
Notes:
Since this is for a simulator, I
don't really need cryptographic
randomness.
It would be best if this is a 32 bit number.
|
If you can afford to use Boost, then there is a UUID library that should do the trick. It's very straightforward to use - check the documentation and this answer.
|
543,507
| 543,557
|
In the C++ Boost libraries, why is there a ".ipp" extension on some header files
|
In the C++ Boost libraries, why is there a ".ipp" extension on some header files?
It seems like they are header files included by the ".hpp" file of the same name.
Is this convention common outside of Boost?
What is the justification for having a special file type?
|
Explanation from one of the template gurus:
If you want to split up your template sources into interface and
implementation (there are lots of good reasons to do that, including
controlling instantiation), you can't very well use the same name
(foo.hpp) twice, and foo.cpp wouldn't be appropriate for either one.
foo.ipp clearly delineates the file as an implementation file intended to
be #included in foo.hpp.
|
543,515
| 543,537
|
Structs vs classes in C++
|
When should someone use structs instead of classes or vice versa in C++? I find myself using structs when a full-blown class managing some information seems like overkill but want to indicate the information being contained are all related. I was wondering what are some good guidelines to be able to tell when one is more appropriate than the other?
Edit:
Found these links while reading the material Stack Overflow indicated was related after the question was submitted:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++?
|
Technically, the only difference between the two is that structs are public: by default and classes are private:
Other than that, there is no technical difference.
struct vs class then becomes a purely expressive nuance of the language.
Usually, you avoid putting complicated methods in a struct, and most of the time structs data members will stay public. In a class you want to enforce strong encapsulation.
struct = data is public, with very simple helper methods
class = strongly encapsulated, data is modified / accessed only through methods
|
543,697
| 543,762
|
#include all .cpp files into a single compilation unit?
|
I recently had cause to work with some Visual Studio C++ projects with the usual Debug and Release configurations, but also 'Release All' and 'Debug All', which I had never seen before.
It turns out the author of the projects has a single ALL.cpp which #includes all other .cpp files. The *All configurations just build this one ALL.cpp file. It is of course excluded from the regular configurations, and regular configurations don't build ALL.cpp
I just wondered if this was a common practice? What benefits does it bring? (My first reaction was that it smelled bad.)
What kinds of pitfalls are you likely to encounter with this? One I can think of is if you have anonymous namespaces in your .cpps, they're no longer 'private' to that cpp but now visible in other cpps as well?
All the projects build DLLs, so having data in anonymous namespaces wouldn't be a good idea, right? But functions would be OK?
|
It's referred to by some (and google-able) as a "Unity Build". It links insanely fast and compiles reasonably quickly as well. It's great for builds you don't need to iterate on, like a release build from a central server, but it isn't necessarily for incremental building.
And it's a PITA to maintain.
EDIT: here's the first google link for more info: http://buffered.io/posts/the-magic-of-unity-builds/
The thing that makes it fast is that the compiler only needs to read in everything once, compile out, then link, rather than doing that for every .cpp file.
Bruce Dawson has a much better write up about this on his blog: http://randomascii.wordpress.com/2014/03/22/make-vc-compiles-fast-through-parallel-compilation/
|
543,812
| 545,515
|
Calculate SLOC GCC C/C++ Linux
|
We have a quite large (280 binaries) software project under Linux and currently it has a very dispersed code structure - that means one can't [work out] what code from the source tree is valid (builds to deployable binaries) and what is deprecated. But the Makefiles are good. We need to calculate C/C++ SLOC for entire project.
Here's a question - can I find out SLOC GCC has compiled? Or maybe I can gain this information from binary (debug info probably)? Or maybe I can find out what source files was the binary compiled from and use this info to calculate SLOC?
Thanks
Bogdan
|
The first thing you want is an accurate list of what you actually compiled. You can achieve this by using a wrapper script instead of gcc.
The second list you want is the list of files that were used for this. For this, consult the dependency list (as you said that was correct). (Seems you'd need make --print-data-base)
Then, sort and deduplicate the list of files, and throw out system headers. For each remaining file, determine the SLOC count using your prefered tool.
|
544,079
| 544,107
|
How do I use glutBitmapString() in C++ to draw text to the screen?
|
I'm attempting to draw text to the screen using GLUT in 2d.
I want to use glutBitmapString(), can someone show me a simple example of what you have to do to setup and properly use this method in C++ so I can draw an arbitrary string at an (X,Y) position?
glutBitmapString(void *font, const unsigned char *string);
I'm using linux, and I know I need to create a Font object, although I'm not sure exactly how and I can supply it with the string as the second arguement. However, how do I also specify the x/y position?
A quick example of this would help me greatly. If you can show me from creating the font, to calling the method that would be best.
|
You have to use glRasterPos to set the raster position before calling glutBitmapString(). Note that each call to glutBitmapString() advances the raster position, so several consecutive calls will print out the strings one after another. You can also set the text color by using glColor(). The set of available fonts are listed here.
// Draw blue text at screen coordinates (100, 120), where (0, 0) is the top-left of the
// screen in an 18-point Helvetica font
glRasterPos2i(100, 120);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glutBitmapString(GLUT_BITMAP_HELVETICA_18, "text to render");
|
544,206
| 544,225
|
Is it possible (or ok) to have a std::list of std::list's?
|
I have a std::list of Points (that simply store an x, y). Each one of these points represents a polygon, which I later draw.
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
std::list <Point> currentPolygon;
I would like to have a list of these polygons (lists themselves).
Is this possible? How do I have a std::list of a list of Points (so I can store more than one polygon).
|
You could use this:
std::list< std::list<Point> > polygons;
To make things easier, use typedefs.
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
typedef std::list<Point> PolygonType;
typedef std::list<PolygonType> PolygonsType;
|
544,397
| 544,412
|
Concat strings and numbers in C++?
|
I'm trying to concat "(" + mouseX + ", " + mouseY ")". However, mouseX and mouseY are ints, so I tried using a stringstream as follows:
std::stringstream pos;
pos << "(" << mouseX << ", " << mouseY << ")";
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str());
And it doesn't seem to work.
I get the following error:
mouse.cpp:75: error: cannot convert std::basic_string<char, std::char_traits<char>, std::allocator<char> >' toconst char*' for argument 2' tovoid _glutBitmapString(void*, const char*)'
What am I doing wrong in this basic string + integer concatenation?
|
glutBitmapString() expects a char* and you're sending it a string. use .c_str() on the string like so:
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());
|
544,462
| 544,488
|
Global variables and scope - C++
|
I am having small problem in making a global variable works. I am using Visual Studio 2008 and standard C++.
I have two projects, one is a static library and second one is a test program which uses this library. I have a global variable in global.h like
#ifndef GLOBAL_H
#define GLOBAL_H
#include <string>
extern std::string globalWord;
#endif // GLOBAL_H!
I have a global.cpp where I am initializing this variable. This variable is used inside my library project. I am setting a value to this variable from the test project, but that value is not getting reflected in the library project.
I have debugged and it shows the new value in test project, but when the control reaches the library project, this variable value shows empty. So is this global variable's scope only limited to the project where it belongs to?
Or is there a better way to do this? I don't want to modify my function or constructor parameters in my library to pass this value.
Any help would be great.
Edit:
Here is how this variable is declared in global.cpp
#include <string>
#include "../global.h"
std::string globalWord = "";
This is how I used it in my library
#include "../global.h"
string text = globalWord;
Thanks
|
Don't use global variables. Just don't. Much better, if you HAVE to have globally accessible data, is to use a global function which will return globalWord, like this:
std::string globalWord()
{
static std::string word("Hi Mom");
return word;
}
This saves you from initialization order issues (read Effective C++ item #4).
|
544,842
| 544,847
|
Creating a type alias for a templated class
|
Instead of using
std::vector<Object> ObjectArray;
I would like it to be
MyArray<Object> ObjectArray;
with all the std::vector methods preserved. (like push_back(), reserve(), ...etc)
However, using
typedef std::vector MyArray;
won't work. Should I use template instead? How?
|
What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x.
For now, here's a possible workaround:
template<class T> struct My {
typedef std::vector<T> Array;
};
My<Object>::Array ObjectArray
Whether or not that is better than simply using std::vector directly, I'll leave to you to decide.
|
544,845
| 544,897
|
How am I accidentally overwriting when referencing these pointers?
|
Last question for tonight, I promise. These pointers are giving me a serious headache.
I have a std::list<Point> called Polygon and a std::list of Polygons defined like:
typedef std::list<Point> Polygon;
typedef std::list<Polygon> PolygonList;
// List of all our polygons
PolygonList polygonList;
I created the method below to attempt to delete the nearest Point from an (x,y), checking all of my Polygons within my polygonList.
void deleteNearestPoint(int x, int y)
{
y = screenHeight - y;
Polygon &closestPolygon = polygonList.front();
Polygon::iterator closestPoint = closestPolygon.begin();
float closestDistance = sqrt(pow(x - closestPoint->x, 2) + pow(y - closestPoint->y, 2));
// Search PolygonList
PolygonList::iterator listIter;
Polygon::iterator iter;
for(listIter = polygonList.begin(); listIter != polygonList.end(); listIter++)
{
Polygon &tempPolygon = *listIter;
for(iter = tempPolygon.begin(); iter != tempPolygon.end(); iter++)
{
const float distance = sqrt(pow(x - iter->x, 2) + pow(y - iter->y, 2));
if (distance < closestDistance)
{
closestPolygon = *listIter;
closestPoint = iter;
closestDistance = distance;
}
}
}
closestPolygon.erase(closestPoint);
redraw();
}
However, somewhere I have a pointer or reference variable screwing me up. This code compiles but acts in a very strange way.
I've written a debug statement and lets say I have 3 polygons in my polygon list like so:
Polygon #: 0
Point: (448, 43)
Point: (469, 177)
Point: (374, 123)
Polygon #: 1
Point: (295, 360)
Point: (422, 350)
Point: (315, 266)
Point: (295, 360)
Polygon #: 2
Point: (143, 202)
Point: (301, 203)
Point: (222, 100)
Point: (143, 202)
Now, lets say I try and use the delete function giving it an x/y close to point 422, 350 The desired result would be it simply deleting that point (422, 350) from Polygon #1 but instead I get this:
Polygon #: 0
Point: (295, 360)
Point: (422, 350)
Point: (315, 266)
Point: (295, 360)
Polygon #: 1
Point: (295, 360)
Point: (315, 266)
Point: (295, 360)
Polygon #: 2
Point: (143, 202)
Point: (301, 203)
Point: (222, 100)
Point: (143, 202)
It did delete (422, 350) but it also has the strange side effect of overwriting Polygon#0 to what Polygon#1 was before the delete of its point.
I know I'm using a pointer or reference incorrectly in my method. Can someone point out what I could possibly be doing that is causing this? I think it is because my &closestPolygon is declared as a reference, but I get compile errors if I try to set it as anything else.
|
Other answers have pointed out what caused the error. As a general advice I would suggest not using references except in function arguments. The semantics are confusing, also for someone that will try to read your code. Try rewriting to something like this (I didn't test the code):
void deleteNearestPoint(int x, int y)
{
y = screenHeight - y;
PolygonList::iterator closestPolygon = polygonList.begin();
Polygon::iterator closestPoint = closestPolygon->begin();
float closestDistance = sqrt(pow(x - closestPoint->x, 2) + pow(y - closestPoint->y, 2));
// Search PolygonList
PolygonList::iterator listIter;
Polygon::iterator iter;
for(listIter = polygonList.begin(); listIter != polygonList.end(); listIter++)
{
for(iter = listIter->begin(); iter != listIter->end(); iter++)
{
const float distance = sqrt(pow(x - iter->x, 2) + pow(y - iter->y, 2));
if (distance < closestDistance)
{
closestPolygon = listIter;
closestPoint = iter;
closestDistance = distance;
}
}
}
closestPolygon->erase(closestPoint);
redraw();
}
|
544,946
| 1,403,433
|
Building a library across platforms without running all of the platforms
|
I have a small piece of code that works as a plugin for a larger graphics application. The development platform is Qt with c++ code. I've managed to build a .so, .dylib and .dll for linux, MacOS and Windows respectively, but to do so I had to have a machine running each operating system (in my case, running linux [ubuntu] gcc natively, and windows MinGW and MacOS XCode gcc in virtual machines).
Is there a way to build for all 3 platforms from one? I beat my head against this problem a while back, and research to date suggests that it's not easily (or feasibly) done. The code only needs to link against a single header that defines the plugin
API and is built from a fairly basic Makefile (currently with small variations per platform).
|
Better late than never, I just came across IMCROSS
It looks quite promising!
|
545,329
| 545,609
|
Why does StackWalk64 return always true?
|
I tried to make my program dump and save its stack trace when crashes. I installed my own win32 SE handler with _set_se_translator and tried to dump the stack trace with StackWalk64 and finally throw a C++ exception (which actually does the logging when caught).
The code looks like this:
...
_set_se_handlers(WIN32EXCEPTION::Win32ExceptionStuff);
...
void WIN32EXCEPTION::Win32ExceptionStuff(unsigned int Code, struct _EXCEPTION_POINTERS* Info) // static
{
STACKFRAME64 sf64;
sf64.AddrPC.Offset = Info->ContextRecord->Eip;
sf64.AddrStack.Offset = Info->ContextRecord->Esp;
sf64.AddrFrame.Offset = Info->ContextRecord->Ebp;
sf64.AddrPC.Mode= sf64.AddrStack.Mode= sf64.AddrFrame.Mode= AddrModeFlat;
while (StackWalk64(IMAGE_FILE_MACHINE_I386,GetCurrentProcess(),GetCurrentThread(),
&sf64,Info->ContextRecord,0,SymFunctionTableAccess64,SymGetModuleBase64,0))
{
//... Do something with the stack frames
}
throw WIN32EXCEPTION(/*...*/);
}
as I saw in some examples, but there is a problem: StackWalk64 always return true and that while loop becomes infinite. The StackWalk64 only repeats the same frame.
What is the problem, and how to fix?
|
This looks very similar to code I've got, and that does work. The only difference I can see is that my code uses ZeroMemory() to clear the STACKFRAME64 structure before populating any parts of it - this may be required.
|
545,394
| 545,464
|
Combining Predicates
|
Is there any way that you can combine predicates?
Lets say I have something like this:
class MatchBeginning : public binary_function<CStdString, CStdString, bool>
{ public:
bool operator()(const CStdString &inputOne, const CStdString &inputTwo) const
{ return inputOne.substr(0, inputTwo.length()).compare(inputTwo) == 0; }
};
int main(int argc, char* argv[])
{
CStdString myString("foo -b ar -t az");
vector<CStdString> tokens;
// splits the string every time it encounters a "-"
split(myString, tokens, "-", true, true);
vector<CStdString>::iterator searchResult = find_if(tokens.begin(), tokens.end(), not1(bind2nd(MatchBeginning(), "-")));
return 0;
}
This works, but now I'd like to do something like:
searchResult = find_if(tokens.begin(), tokens.end(), bind2nd(MatchBeginning(), "-b") || not1(bind2nd(MatchBeginning(), "-")));
So I'd like to find the first string that starts with "-b" or the first string that does not start with "-". However, this gives me an error (binary '||' undefined).
Is there any way to do this?
|
I can recommend boost.lambda for combining function-objects for such tasks. Although it is a bit heavyweight for such a simple problem. (edit) See the community wiki answer started by xhantt for a good example using STL.
(old, deprecated, answer) You can write your own utility for this, similar:
// here we define the combiner...
template<class Left, class Right>
class lazy_or_impl {
Left m_left;
Right m_right;
public:
lazy_or_impl(Left const& left, Right const& right) : m_left(left), m_right(right) {}
typename Left::result_type operator()(typename Left::argument_type const& a) const {
return m_left(a) || m_right(a);
}
};
// and a helper function which deduces the template arguments
// (thx to xtofl to point this out)
template<class Left, class Right>
lazy_or_impl<Left, Right> lazy_or(Left const& left, Right const& right) {
return lazy_or_impl<Left, Right>(left, right);
}
and then use it: ... lazy_or(bind1st(...), bind1st(...)) ...
|
545,504
| 545,902
|
How to change font/color on MFC dialog for Windows Mobile?
|
Does anyone know how to set font and color on a static text and other controls of MFC dialog for Windows Mobile?
Where can I get the list of supported fonts?
Thanks!
|
Colors are changed via SetBkColor and SetTextColor.
Here is an example of enumerating fonts.
|
545,532
| 545,555
|
What's the simplest way to create an STL - identity map?
|
I'd like to initialize a map - object "id" with identities from 0 to n-1, i.e.
id[0] = 0
id[1] = 1
.
.
id[n-1] = n-1
Is there a simple way - a one-liner, a method inside the map-object, simply something really simple - that does that?
|
You could use the
template <class InputIterator>
map(InputIterator f, InputIterator l,
const key_compare& comp)
form of the constructor, but you'd need to build an InputIterator that worked as a generator function over the range you want. That'd be a whole lot more typing than just using a for loop.
|
546,596
| 546,689
|
What is the best data structure for representing nodes in 3D space?
|
... and thanks for reading...
I'm still learning the ropes so please be forgiving... ;-)
I am writing a function that meshes a solid in space. The mesh is done by using objects of a "Node" class and each node is represented by:
int id
double p
double r
Initially I thought that a map would be the way to go: with a map I can make the association between the "id" key and the second key (a pointer to the node object).
Something like this:
int nodeId;
Node *node;
std::map<int, Node *> NodeMap;
Then, when I create the nodes I just call the "new" operator. E.g in a for loop I do something like this:
node = new Node(i); // the node constructor sets the id to the value of i.
and I add the new node to the map:
NodeMap[i] = node;
But.... I realized that I will need to do a lookup in the map not by first key (the id) but by the p and r parameters (the coordinates of the node).
In other words I will need something that returns the node id given the values of p and r.
A map is a perfect container if the lookup is done using the integer first key (id).
Does anyone have a suggestion on how to solve this particular problem?
Thanks much!
AsvP.
|
A map<> won't work. C++ associative containers work on the basis of key equality, and comparing floating-point numbers for equality doesn't work at all well.
It sounds like you need to find a node, given x and y. The best way will depend on what you're trying to accomplish. Are you trying to find the nearest node, given the coordinates, or are you going to calculate coordinates that are very close to a node, and then you need to find the node?
For the second, you'll probably be well off sorting the nodes on either the x or y coordinate (I'll assume the x), and doing a binary search to find which nodes have x coordinates very close to your given x. That will generally select a small number of nodes, which can be searched for the approximately correct y.
(Of course, if the nodes are in some sort of predictable grid, you should be able to provide some means to calculate directly, like round x and y to nearest integer if you've got integral lattice points.)
If you need to find the closest node, well, that gets a bit complicated. I don't know enough about this to help much, but there are resources for geometric algorithms.
|
546,669
| 546,678
|
C++ code analysis tools
|
I'm currently in the process of learning C++, and because I'm still learning, I keep making mistakes.
With a language as permissive as C++, it often takes a long time to figure out exactly what's wrong -- because the compiler lets me get away with a lot. I realize that this flexibility is one of C++'s major strengths, but it makes it difficult to learn the basic language.
Is there some tool I can use to analyze my code and make suggestions based on best practices or just sensible coding? Preferably as an Eclipse plugin or linux application.
|
Enable maximum compiler warnings (that's the -Wall option if you're using the Gnu compiler).
'Lint' is the archetypical static analysis tool.
valgrind is a good run-time analyzer.
|
546,993
| 547,058
|
Problems with const set&. Compiler/STL bug or non-portable usage?
|
Are there any language lawyers in the house?
Should the following code compile?
include <set>
bool fn( const std::set<int>& rSet )
{
if ( rSet.find( 42 ) != rSet.end() ) return true;
return false;
}
On one of the platforms (Sun Workshop) this does not compile. It reports that the find function returned an iterator and the end function that returned a const_iterator and that it does not have a valid comparison operator between those types.
The following does compile:
include <set>
bool fn( std::set<int>& rSet )
{
if ( rSet.find( 42 ) != rSet.end() ) return true;
return false;
}
|
It should compile. Set includes 2 find() functions and 2 end() functions (const and non-const versions). It sort of sounds like Sun's STL is broken somehow. Since you are passing in a const reference, the compiler should be able to select the correct find() and end() functions.
|
546,997
| 547,007
|
Use #ifdefs and #define to optionally turn a function call into a comment
|
Is it possible to do something like this
#ifdef SOMETHING
#define foo //
#else
#define foo MyFunction
#endif
The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction.
I've seen __noop used, but I don't believe I can use that.
EDIT(s):
I don't think I can really use a macro here, because MyFunction takes a variable number of arguments.
Also, I'd like to make it so the arguments are NOT evaluated! (So doing something like commenting out the body of MyFunction doesn't really give me what I need, as the arguments will still be evaluated)
|
Try this:
#ifdef SOMETHING
#define foo(x)
#else
#define foo(x) MyFunction(x)
#endif
If your function has several arguments, then:
#ifdef SOMETHING
#define foo(x,y,z)
#else
#define foo(x,y,z) MyFunction(x,y,z)
#endif
If your function has a variable number of arguments, then your compiler may support so-called "variadic macros", like this:
#ifdef SOMETHING
#define foo(...)
#else
#define foo(...) MyFunction(__VA_ARGS__)
#endif
The reason which I've seen this kind of thing used in practice is to get rid of logging functions from a release build. However, see also Separate 'debug' and 'release' builds? in which people question whether you should even have different builds.
Alternatively, instead of redefining the function call as nothing, Jonathan's comment to this answer suggested doing something like the following:
#ifdef SOMETHING
#define foo(...) do { if (false) MyFunction(__VA_ARGS__) } while (0)
#else
#define foo(...) do { if (true) MyFunction(__VA_ARGS__) } while (0)
#endif
The reasoning for doing this is so that the function call is always compiled (so it won't be left with gratuitous errors like references to deleted variables), but only called when needed: see Kernighan & Pike The Practice of Programming and also the Goddard Space Flight Center programming standards.
From a debug.h file (originating from 1990, and therefore not using __VA_ARGS__):
/*
** Usage: TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
*/
#ifdef DEBUG
#define TRACE(x) db_print x
#else
#define TRACE(x) do { if (0) db_print x; } while (0)
#endif /* DEBUG */
With C99, there's no longer a need for the double parentheses trick. New code should not use it unless C89 compatibility is an issue.
|
547,011
| 548,809
|
How do you use bitwise flags in C++?
|
As per this website, I wish to represent a Maze with a 2 dimensional array of 16 bit integers.
Each 16 bit integer needs to hold the following information:
Here's one way to do it (this is by no means the only way): a 12x16 maze grid can be represented as an array m[16][12] of 16-bit integers. Each array element would contains all the information for a single corresponding cell in the grid, with the integer bits mapped like this:
(source: mazeworks.com)
To knock down a wall, set a border, or create a particular path, all we need to do is flip bits in one or two array elements.
How do I use bitwise flags on 16 bit integers so I can set each one of those bits and check if they are set.
I'd like to do it in an easily readable way (ie, Border.W, Border.E, Walls.N, etc).
How is this generally done in C++? Do I use hexidecimal to represent each one (ie, Walls.N = 0x02, Walls.E = 0x04, etc)? Should I use an enum?
See also How do you set, clear, and toggle a single bit?.
|
Use std::bitset
|
547,214
| 547,264
|
winsock weirdness (c++)
|
I am trying to implement a function called "inet_pton" which will convert a string representation of an IPv4 or IPv6 (like "66.102.1.147" [google]) into binary network-byte ordered form. Here is the relevant part of my code:
#if defined WIN32
int inet_pton (int af, const char *src, void *dst)
{
const void *data;
size_t len;
struct addrinfo hints, *res;
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_NUMERICHOST;
if (getaddrinfo (src, NULL, &hints, &res))
{
std::cout << "ERROR : inet_pton() in " << __FILE__ << " at line " << __LINE__ << std::endl;
std::cout << " : getaddrinfo() failed to get IP address info for \"" << src << "\"" << std::endl;
return 0;
}
...
So src is the incoming IP string. However, I always get an error like
getaddrinfo() failed to get IP address info for "66.102.1.147"
Can anyone with winsock experience comment? I also tried another method, the function
WSAStringToAddress ((LPTSTR)src, af, NULL, (LPSOCKADDR) &sa, &address_length)
But it always returns the error code WSAEINVAL, indicating an invalid IP string. This makes no sense to me. I'm using VS2005 as my IDE.
|
Well, for a start you're asking for a stream socket with UDP as a protocol and that just isn't going to happen.
Try with:
hints.ai_family = af;
hints.ai_socktype = 0;
hints.ai_protocol = 0;
hints.ai_flags = AI_NUMERICHOST;
and memset it to zero first as it has extra members that you're not setting...
Also in my code I pass an empty string for the port or service when I don't have one rather than a null. The docs don't seem to specify what to do when you don't have a value; but either way an empty string works for me.
Oh, and as always in these situations, it would be useful to know what value WSAGetLastError() returns...
|
547,290
| 547,439
|
Is the "empty base optimization" in GCC configurable?
|
Consider these types:
struct A {};
struct B : A { int i; };
sizeof(A) > 0 as required by the standard.
sizeof(B) should be 4 due to the empty base optimization. Yet on GCC 4.1.1 it's 5 (I'm using a pack of 1 in this area). And inconsistently - some of my files are getting it, some are not. Can't be sure what the differences are yet, we have a large prjoect.
On the other three compilers I'm using (by Microsoft and Freescale), I don't have this problem. The empty base optimization is optional apparently, according to this article.
Is there a compiler option or pragma to tune this in GCC 4.1.1? I can work around the issue but I would like to understand what's going on first. I Googled for a while and can't seem to find anything.
|
This always happens. I post immediately before I figure it out. Maybe the act of posting gets me thinking in a different way..
So in my question the sample was a little bit over-simplified. It's actually more like this:
struct Base {};
struct C1 : Base { int i; }
struct C2 : Base { C1 c; int i; }
sizeof(C1) is correctly 4 on all platforms, but sizeof(C2) is 9 instead of 8 on GCC. And... apparently GCC is the only thing that gets it right, according to the last bit of the article I linked to in the original question. I'll quote it (from Nathan Meyers) here:
A whole family of related "empty subobject" optimizations are possible, subject to the ABI specifications a compiler must observe. (Jason Merrill pointed some of these out to me, years back.) For example, consider three struct members of (empty) types A, B, and C, and a fourth non-empty. They may, conformingly, all occupy the same address, as long as they don't have any bases in common with one another or with the containing class. A common gotcha in practice is to have the first (or only) member of a class derived from the same empty base as the class. The compiler has to insert padding so that they two subobjects have different addresses. This actually occurs in iterator adapters that have an interator member, both derived from std::iterator. An incautiously-implemented standard std::reverse_iterator might exhibit this problem.
So, the inconsistency I was seeing was only in cases where I had the above pattern. Every other place I was deriving from an empty struct was ok.
Easy enough to work around. Thanks all for the comments and answers.
|
547,758
| 547,770
|
Read data with varying formats in C++
|
I'm creating my first real binary parser (a tiff reader) and have a question regarding how to allocate memory. I want to create a struct within my TiffSpec class for the IFD entries. These entries will always be 12 bytes, but depending upon the type specified in that particular entry, the values at the end could be of different types (or maybe just an address to another location in the file). What would be the best way to go about casting this sort of data? The smallest size memory I believe I would be dealing with would be 1 byte.
|
In C++ you should use a union.
This is a mechanism by which you can define several, overlapping data types, possibly with a common header.
See this article for how to use unions for exactly your problem -- a common header with different data underneath.
|
547,833
| 548,072
|
Concrete class specific methods
|
I have an interesting problem. Consider this class hierachy:
class Base
{
public:
virtual float GetMember( void ) const =0;
virtual void SetMember( float p ) =0;
};
class ConcreteFoo : public Base
{
public:
ConcreteFoo( "foo specific stuff here" );
virtual float GetMember( void ) const;
virtual void SetMember( float p );
// the problem
void foo_specific_method( "arbitrary parameters" );
};
Base* DynamicFactory::NewBase( std::string drawable_name );
// it would be used like this
Base* foo = dynamic_factory.NewBase("foo");
I've left out the DynamicFactory definition and how Builders are
registered with it. The Builder objects are associated with a name
and will allocate a concrete implementation of Base. The actual
implementation is a bit more complex with shared_ptr to handle memory
reclaimation, but they are not important to my problem.
ConcreteFoo has class specific method. But since the concrete instances
are create in the dynamic factory the concrete classes are not known or
accessible, they may only be declared in a source file. How can I
expose foo_specific_method to users of Base*?
I'm adding the solutions I've come up with as answers. I've named
them so you can easily reference them in your answers.
I'm not just looking for opinions on my original solutions, new ones
would be appreciated.
|
The cast would be faster than most other solutions, however:
in Base Class add:
void passthru( const string &concreteClassName, const string &functionname, vector<string*> args )
{
if( concreteClassName == className )
runPassThru( functionname, args );
}
private:
string className;
map<string, int> funcmap;
virtual void runPassThru( const string &functionname, vector<string*> args ) {}
in each derived class:
void runPassThru( const string &functionname, vector<string*> args )
{
switch( funcmap.get( functionname ))
{
case 1:
//verify args
// call function
break;
// etc..
}
}
// call in constructor
void registerFunctions()
{
funcmap.put( "functionName", id );
//etc.
}
|
548,751
| 548,859
|
Should I become proficient with STL libraries before learning BOOST alternatives?
|
Does it make sense to restrict yourself to the STL libraries when learning C++ and then tackle boost and its additions after you have become fairly proficient with vanilla C++?
Or should you dive right into BOOST while learning C++?
|
The STL has some core concepts to it. Boost builds on and expands on them. If you understand them, then moving right on to Boost may be of use to you. If not, I would start with the STL.
The distinction between the various container types (sequences like vector, list and deque, and associations like map, set and their multi* and unordered_* varieties). Sometimes you can swap one for the other -- sometimes you can't. Know their strengths and their limits.
The role of iterators, and how they provide a bridge between containers and algorithms. (This one I find I use over and over).
Why there are standard algorithms: they are often tiny amounts of code, so it may not be obvious why they exist. Learn which containers they work with, and how to specialize them for particular cases (for example see how generic copy differs from copy specialized for const char *).
How and when traits classes are used.
How to use binders (bind1st, ptr_fun and mem_fun): the syntax can obscure their utility.
How to use string -- and when not to use it. (All string classes have tradeoffs: learning the pros and cons of the standard one is educational).
The difference between streams and streambufs: how to use the former to do formatted I/O (try reading a string from a stream: it's not as straightforward as it should be), and the latter to do low-level fast I/O.
The principles used to design the STL are built upon and expanded on by the Boost libraries. If you get them, Boost is manageable. If you don't, and Boost ends up hard to follow, you can go back to the STL to get your bearings.
(In general Boost really pushes the boundaries of the language. If you decide you want to really push your own knowledge of C++, and test if you really know what you think you know then it can provide an interesting challenge. I've used C++ for more than a dozen years, have taught other people how to use it, have acquired proficiency in many more high-level languages since then and Boost still surprises me. It's very useful, but its not trivial).
|
548,819
| 548,858
|
How to determine a process "virtual size" (WinXP)?
|
I have a program that needs a lot of memory, and it crashes as soon as the 2GB virtual address space is reached. Sysinternals process explorer displays this as "virtual size" column.
How can I determine this "virtual size" with C (or C++) code?
Ok, I have to query a performance counter for "Virtual Bytes". Perfmon shows the query string (or how it is called) as, for example, '\Process(firefox)\Virtuelle Größe' on my German Win XP installation.
How do I determine the query string for the 'current process', and is there a non-localized name for it?
|
According to MSDN: Memory Performance Information PROCESS_MEMORY_COUNTERS_EX.PrivateUsage is the same as VM Size in Task Manager in Windows XP. GetProcessMemoryInfo should work:
PROCESS_MEMORY_COUNTERS_EX pmcx = {};
pmcx.cb = sizeof(pmcx);
GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx), pmcx.cb);
Now pmcx.PrivateUsage holds the VM Size of the process.
|
548,969
| 548,994
|
Using ": number" while declaring variables
|
If i declare an enum as follows:
typedef enum A
{
a = 0x00000001,
b = 0x00000002
} AObj;
Now if i declare a variable of AObj as follows what does this mean?
AObj myAObj : 2;
|
It is a way of specifying the number of bits used.
That is 2 means 2 bits.
Also note that this is only useful when used with other bit fields in the same struct as alignment and padding will cause the memory to be skipped.
|
549,031
| 549,089
|
How do you include images as resources in a C++ executable?
|
Is it possible include images (jpegs) as resources in a win32 c++ executable? If so how?
|
Here's the MSDN documentation about resource files.
http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx
|
549,206
| 549,210
|
Public boost::signal object
|
I make my boost::signals public because I'm lazy.
class Button {
public:
signal<void()> clicked;
};
int main() {
Button btn;
btn.clicked.connect(handleClick);
}
... rather than encapsulating with a Button::OnClicked(boost::function<void()>).
Is this going to come back and bite me?
|
It depends.
It has bitten me before when I wanted to add some special logic each time an object connected to another object's signals. This is the most likely case to bite you.
Also, it can make it difficult to keep track of exactly when other objects are connecting to any given object.
I would say hide the connections behind a function to be on the safe side.
I usually use a macro to do the vanilla function definition.
#define SIGNAL(slot,name) connection name(function<slot> func) { return _##name##.connect(func);}
And then in a class definition:
SIGNAL(void(),clicked)
This assumes you follow the convention of naming the signal '_clicked' but you can substitute any convention. It generally keeps the interface cleaner for all of your classes. When you want to add special connection logic you can, without changing all of the other objects that use the signal.
EDIT
One instance was when the signal object was actually moved to a delegate implementation inside another class, but it still made sense for objects to connect through the original class. This broke all of the places that tried to connect to it. If they had been using function accessors to connect, it would have been as simple as changing the function to look up the signal in the delegate. But as it was it broke all the users of the original class.
Or, when I wanted to log each time something connected to a specific signal. This was just for debugging purposes, but it can be very helpful if you suspect something wonky is going on like cycles in your signal connections.
|
549,249
| 591,068
|
Polymorphism across C++ and Ruby using SWIG
|
I use SWIG to wrap a Ruby script around a C++ library. In Ruby, I can inherit from a C++ class, but I cannot pass the resulting pointer to a C++ function in a polymorphic way.
Here is a concrete example. The SWIG interface file defines base class Animal with virtual function sound():
[animals.i]
%module(directors="1") animals
%{
#include "animals.h"
%}
// Apply the 'director' feature to a virtual function,
// so that we can override it in Ruby.
%feature("director") Animal::sound;
class Animal {
public:
Animal();
virtual ~Animal();
virtual void sound();
};
class Dog : public Animal {
public:
Dog();
virtual ~Dog();
virtual void sound();
};
// This function takes an Animal* and calls its virtual function sound().
void kick(Animal*, int);
Note that I use SWIG directors for cross-language polymorphism, but this does not seem to work. The Ruby script looks like this:
[tst.rb]
require 'animals'
include Animals
dog= Dog.new # Instantiate C++ class
kick(dog, 3) # Kick the dog 3 times => It barks 3 times.
# So far so good.
class Cat < Animal # Inherit from a C++ class
def initialize
puts "Creating new cat"
end
def sound
puts "Meow"
end
end
cat= Cat.new # Instantiate Ruby class
kick(cat, 9) # This does not fly.
The final line in the script produces this error:
Expected argument 0 of type Animal *, but got Cat #<Cat:0xb7d621c8>
So somehow SWIG does not allow me to treat the Ruby object as a pointer-to-Animal. Any ideas?
|
I got a solution to my problem from Tobias Grimm at the swig-user mailing list.
The first part of the problem is SWIG's misleading error message.
The message seems to suggest that I pass the wrong type of pointer to my C++
function, but this is not the case. If you check the class of the exception
in Ruby, it's ObjectPreviouslyDeleted, meaning that the underlying C struct pointer
of my Cat class is NULL. So the real problem is that the pointer is NULL,
not that it has the wrong type.
The pointer is NULL because I simply forgot to call "super" in Cat's initialize()
method. This way, with the creation of Cat no underlying C struct gets allocated,
because the Animal constructor never gets called.
Forgetting to call 'super' is a very common Ruby-beginner's mistake, especially
for people like me who come from C++, who are used to automatic constructor chaining.
So all I had to do was add a call to 'super':
class Cat < Animal # Inherit from a C++ class
def initialize
puts "Creating new cat"
super()
end
def sound
puts "Meow"
end
end
This now works fine. Thanks, Tobias.
|
549,849
| 549,857
|
Preventing Virtual Method Implementation in C++
|
I have the following class hierarchy in C++:
class Base {
virtual void apply() = 0;
};
class Derived : public Base {
virtual void apply() {
// implementation here that uses derived_specialty
}
virtual void derived_specialty() = 0;
};
class Implementation : public Derived {
virtual void derived_specialty() {
// implementation
}
};
I'd like to guarantee that classes at the level of Implementation don't supply their own implementation of apply, and that they only implement derived_specialty. Is there any way to guarantee that classes inheriting from Derived will not implement apply, so that the Derived::apply implementation is used? My understanding is that in C++, a method made virtual in the Base class is virtual all the way down the inheritance hierarchy, but if there are any tricks in C++ to accomplish, I'd be interested in hearing about them.
I'm always surprised by the things that are allowed by C++, so I thought it was worth asking. :)
|
You can kind of do it by composition:
class Base {
virtual void apply();
};
class Derived : public Base {
class IImplementation {
virtual void derived_specialty() = 0;
};
IImplementation& m_implementation;
Derived(IImplementation& implementation)
: m_implementation(implementation)
{}
virtual void apply() {
// implementation here that uses m_implementation.derived_specialty
}
};
class Implementation : Derived::IImplementation {
virtual void derived_specialty() {
// implementation
}
};
Other classes can still subclass Derived and override the apply method, but your Implementation class is no longer one of these classes.
|
549,983
| 550,137
|
Not necessary to export class with only virtual/inline functions?
|
In C++ on Win32:
Suppose I have a DLL with a header file that declares a class. The DLL exports some means of obtaining a pointer/reference to an instance of that class, such as a factory function.
Am I correct in believing that it is not necessary to mark that class as exported using __declspec if one is only going to call virtual or inline functions on its instances?
Conversely, is it necessary to export the class declaration if one wishes to call nonvirtual member functions?
|
Am I correct in believing that it is not necessary to mark that class as exported using __declspec if one is only going to call virtual or inline functions on its instances?
Yes,this is correct, and that's what COM do, the DLL only expotys 4 methods, one of them returns to the class factory, which all its members are pure virtual functions.
Conversely, is it necessary to export the class declaration if one wishes to call statically defined member functions?
No, just export the static member functions.
|
550,035
| 550,048
|
vector<string> or vector<char *>?
|
Question:
What is the difference between:
vector<string> and vector<char *>?
How would I pass a value of data type: string to a function, that specifically accepts:
const char *?
For instance:
vector<string> args(argv, argv + argc);
vector<string>::iterator i;
void foo (const char *); //*i
I understand using vector<char *>: I'll have to copy the data, as well as the pointer
Edit:
Thanks for input!
|
This really has nothing to do with vectors specifically.
A char* is a pointer, which may or may not point to valid string data.
A std::string is a string class, encapsulating all the required data that makes up a string, along with allocation and deallocation functionality.
If you store std::string's in a vector, or anywhere else, then everything will just work.
If you store char pointers, you have to do all the hard work of allocating and freeing memory, and ensuring the pointers only ever point to meaningful string data, and determine the length of the strings and so on.
And since char*'s are expected by a lot of C API's as well as part of the C++ standard library, the string class has the c_str() function which returns a char*.
|
550,106
| 550,119
|
Debug-compiled executable: Why not abort gracefully on invalid write to NULL?
|
What I don't understand about C/C++ is:
Yes, everyone uses it to get blazingly fast executables, so they compile with optimization turned on.
But for compilation with debug information turned on, we don't care about speed. So why not include more information in that compile mode, for example detect some segfaults before they happen? Effectively, insert an assert(ptr != NULL) before every access to a pointer ptr. Why can't the compiler do that? Again, that should be off by default, but there should be such a possibility, I think.
EDIT: Some people said that the detection I suggested doesn't make sense or doesn't do anything that the report of segmentation fault wouldn't already do. But what I have in mind is just a more graceful and informative abort, which prints the file name and line number of the offending code, just like an assert() would do.
|
There are a few major problems with your suggestion:
What conditions do you want the compiler to detect? On Linux/x86, unaligned access can cause SIGBUS and stack overflow can cause SIGSEGV, but in both cases it technically is possible to write the application to detect those conditions and fail "gracefully". NULL pointer checks can be detected, but the most insidious bugs are due to invalid pointer access, rather than NULL pointers.
The C and C++ programming languages provide enough flexibility so it is impossible for a runtime to determine with 100% success if a given random address is a valid pointer of an arbitrary type.
What would you like the runtime environment to do when it detects this situation? It can't correct the behavior (unless you believe in magic). It can only continue executing or exit. But wait a minute... that's what already happens when a signal is delivered! The program exits, a core dump is generated, and that core dump can be used by application developers to determine the state of the program when it crashed.
What you're advocating actually sounds like you want to run your application in a debugger (gdb) or through some form of virtualization (valgrind). This is already possible, but it makes no sense to do it by default, because it provides no benefit to non-developers.
Update to respond to comments:
There's no reason to modify the compilation process for debug versions. If you need a "gentle" debug version of the application, you should run it inside of a debugger. It's very easy to wrap your executable in a script that does this for you transparently.
|
550,189
| 550,206
|
Is it safe to `delete this`?
|
In my initial basic tests it is perfectly safe to do so. However, it has struck me that attempting to manipulate this later in a function that deletes this could be a runtime error. Is this true, and is it normally safe to delete this? or are there only certain cases wherein it is safe?
|
delete this is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After delete this returns, your this pointer value does not change, so it is now a dangling pointer that should not be dereferenced. That includes implicit dereferencing using the class's member variables.
It is usually found in reference-counted classes that, when the ref-count is decremented to 0, the DecrementRefCount()/Release()/whatever member function calls delete this.
delete this is typically considered very bad form for many reasons. It is easy to accidentally access member variables after delete this. Caller code might not realize your object has self-destructed.
Also, delete this is a "code smell" that your code might not have a symmetric strategy for object ownership (who allocates and who deletes). An object could not have allocated itself with new, so calling delete this means that class A is allocating an object, but class B is later freeing it[self].
|
550,219
| 550,224
|
Link error using templates
|
I converted a function to a template, and started getting this error. I must not be understanding a limitation of templates. Can someone tell me why this is broken?
I am receiving this error:
Undefined symbols:
"bool foo<int>(int const&, int const&)", referenced from:
_main in file1.o
ld: symbol(s) not found
When I link the following code. The code is simplified, but still fails. The first file contains:
#include <iostream>
template <class T> bool foo (const T&, const T&);
int main ()
{
int left = 1;
int right = 2;
if (foo <int> (left, right))
std::cout << "foo!" << std::endl;
return 0;
}
And the second file contains:
template <class T> bool foo (const T& left, const T& right)
{
return true;
}
|
For the reason Uri gave, template methods are usually defined in the header file. Because yours is a function and not a method of a class, explicitly define it (in the header file which may be included by more than one CPP file) as static or inline.
Put this in your foo.h
template<class T> inline bool foo (const T& left, const T& right)
{
return true;
}
Put this in your main.cpp
#include <iostream>
#include "foo.h"
int main ()
{
int left = 1;
int right = 2;
if (foo <int> (left, right))
std::cout << "foo!" << std::endl;
return 0;
}
The cpp code now sees the whole declaration of the template function.
Other solutions are listed here: How can I avoid linker errors with my template functions?
|
550,223
| 550,288
|
UPDATE: C++ Pointer Snippet
|
Greetings again, and thanks once more to all of you who provided answers to the first question. The following code is updated to include the two functions per the assignment.
To see the original question, click here.
I am pretty sure this fulfills the requirements of the assignment, but once again I would greatly appreciate any assistance. Did I modify the delete statements appropriately? Thanks again.
#include<iostream>
#include<string>
int** createArray(int, int);
void deleteArray(int*[], int);
using namespace std;
int main()
{
int nRows;
int nColumns;
cout<<"Number of rows: ";
cin>>nRows;
cout<<"Number of columns: ";
cin>>nColumns;
int** ppInt = createArray(nRows, nColumns);
deleteArray(ppInt, nRows);
}
int** createArray(int nRows, int nColumns)
{
int** ppInt = new int*[nRows];
for (int nCount = 0; nCount < nRows; nCount++)
{
ppInt[nCount] = new int[nColumns];
}
return ppInt;
}
void deleteArray(int** nPointer, int nRows)
{
for (int nCount = 0; nCount < nRows; nCount++)
{
delete[] nPointer[nCount];
}
delete[] nPointer;
}
P.S. Here is the assignment documentation itself, in case it helps:
(1) Design and implement a function to allocate memory for a 2-D integer array: the function is supposed to take two integers as parameters, one for number of rows and one for number of columns. You need to use “new” operator in this function. Remember that we need to first create an array of pointers. Then, for each pointer in that array, we need to create an array of integers. This function is supposed to return a pointer which points to a 2-D integer array.
(2) Design and implement a function to de-allocate memory for this 2-D array: the function is supposed to have two parameters (a pointer which points to a 2-D integer array, and the other one is number of rows in the array). In the function, you are supposed to de-allocate memory for this 2-D array using the “delete” operator. You should delete each row (an array of integers) first, and then delete the array of pointers.
|
The code looks good.
However, there are some problems you may want to address, for us humans:
Your function signatures (declarations) lack parameter names. More suitable:
int** createArray(int rows, int columns);
void deleteArray(int** array, int rows);
Your function names aren't too descriptive as to what they really create/delete. create2DArray would be a wiser choice, for example.
Your n prefixes to your variables hurt my eyes. numRows or rowCount is more readable.
Similarly, ppInt is crazy. Try array (for nPointer as well, for consistency). (Sadly, you can't write 2dArray.)
Using i as a loop counter is more common than nCount or similar (especially for array indexes). I suggest you use that instead.
Some things which go Above And Beyond, for your personal practice:
Create a class which takes rows and cols as arguments to its constructor. Make sure to deallocate the array automatically.
Use std::vector and create a resize member function for your class. Note that this deviates from the original question, which asked for pointers.
Create a copy function and a clone function to copy data to another 2D array (possibly of a different size!) or clone an existing array.
|
550,418
| 550,425
|
Designing a lazy vector: problem with const
|
I wrote a little "lazy vector" class (or, delayed vector) which is supposed to look like a std::vector and usable wherever a std::vector is used, but it loads its elements "lazily", i.e. it will load element n (and possibly a few more) from disk whenever someone accesses element n. (The reason is that in my app, not all elements fit into memory.)
Here is this LazyVector class, but there is a problem with const member functions that use such a vector, see below.
template<class T>
class LazyVector {
std::vector<T> elems_;
void fetchElem(unsigned n){
// load the n-th elem from disk into elems_ etc
}
public:
const T& operator[](unsigned n) const {
fetchElem(n); // ERROR: ... discards qualifiers
return elems_[n];
}
T& operator[](unsigned n) {
fetchElem(n);
return elems_[n];
}
// and provide some other std::vector functions
};
As I said, there is a problem when a const member function asks for an element of the LazyVector. By nature of the LazyVector, accessing an element is not const, i.e. it will change the vector vec below, which is forbidden in this context. The foo member function must be const and cannot be changed. How can I solve this?
class Foo {
LazyVector<const std::string*> vec;
void fct(int n) const { // fct must be const
const std::string* str = vec[n];
// do something with str
}
};
|
You can either use mutable member data or const_cast in the implementation of your LazyVector class. Thus you can create the illusion of constness needed by your consuming class without actually being const.
|
550,428
| 550,431
|
An odd C++ error: test.cpp:15: error: passing ‘const *’ as ‘this’ argument of ‘*’ discards qualifiers
|
I'm having some trouble with a particular piece of code, if anyone can enlighten me on this matter it would be greatly appreciated, I've isolated the problem down in the following sample:
#include <iostream>
using namespace std;
class testing{
int test();
int test1(const testing& test2);
};
int testing::test(){
return 1;
}
int testing::test1(const testing& test2){
test2.test();
return 1;
}
So what could possibly have cause the following error:
test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers
Thanks a lot!
|
The problem is calling a non-const function test2.test() on a const object test2 from testing::test1.
testing::test1 gets test2 as a parameter const testing &test2. So within testing::test1, test2const. Then in the first line of the function:
test2.test()
The testing::test function is called on test2. That function is not declared with const at the signature end, so it may modify the object it is called on (the this pointer implicitly passed to it), and even though it does not, the compiler assumes so. By letting you call it there, the compiler would let you modify a const variable without an explicit cast, which C++ is not supposed to allow. Therefore to explain the error message:
test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers
this refers to the object the member function (testing::test) operates on, and in this case it is not const, because testing::test was not declared with const, and thus the mismatch is detected when trying to make a non-const pointer (this) refer to a const object (testing), ignoring the const qualifier.
To solve this, decide whether the testing::test function should ever need to modify the object it is called on (the way it is written now it does not, as all it does is return 1, however that may change, so you need to think at what its intended functionality is). If it should, then obviously calling it on a const object is bad, although you can use const_cast to ask the compiler to override that, but this is dangerous. If it should not, then mark it const, so that it can be called on const objects as well:
class testing{
int test1() const;
// ...
}
int testing::test() const {
// ...
}
|
550,451
| 550,457
|
Will new return NULL in any case?
|
I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement makes code look very ugly.
|
VC6 was non-compliant by default in this regard. VC6's new returned 0 (or NULL).
Here's Microsoft's KB Article on this issue along with their suggested workaround using a custom new handler:
Operator new does not throw a bad_alloc exception on failure in Visual C++
If you have old code that was written for VC6 behavior, you can get that same behavior with newer MSVC compilers (something like 7.0 and later) by linking in a object file named nothrownew.obj. There's actually a fairly complicated set of rules in the 7.0 and 7.1 compilers (VS2002 and VS2003) to determine whether they defaulted to non-throwing or throwing new.
It seems that MS cleaned this up in 8.0 (VS2005)—now it always defaults to a throwing new unless you specifically link to nothrownew.obj.
Note that you can specify that you want new to return 0 instead of throwing std::bad_alloc using the std::nothrow parameter:
SomeType *p = new(std::nothrow) SomeType;
This appears to work in VC6, so it could be a way to more or less mechanically fix the code to work the same with all compilers so you don't have to rework existing error handling.
|
550,455
| 550,462
|
Compile error: Undefined symbols: "_main", referenced from: start in crt1.10.5.o
|
I have the following code:
#include <iostream>
using namespace std;
class testing{
int test() const;
int test1(const testing& test2);
};
int testing::test() const{
return 1;
}
int testing::test1(const testing& test2){
test2.test();
return 1;
}
after compilation, it gives me the following error:
Undefined symbols:
"_main", referenced from:
start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
Why is it complaining about main? Can't i declare main in another file and include this one?
Thanks a lot!
|
You have tried to link it already:
g++ file.cpp
That will not only compile it, but try to already create the executable. The linker then is unable to find the main function that it needs. Well, do it like this:
g++ -c file.cpp
g++ -c hasmain.cpp
That will create two files file.o and hasmain.o, both only compiled so far. Now you can link them together with g++:
g++ -omy_program hasmain.o file.o
It will automatically figure out that those are files already compiled, and invoke the linker on them to create a file "my_program" which is your executable.
|
550,548
| 550,564
|
Odd behavior with operator>= overloading
|
I'm having a strange behavior with an operator overloading in C++. I have a class, and I need to check if its contents are greater or equal to a long double. I overloaded the >= operator to make this check, my declaration is as follows:
bool MyClass::operator>=(long double value) const;
I have to say that I also have a cast-to-long-double operator for my class, that works without exceptions only under certain conditions.
Now, when I use this operator, the compiler complains that there's an ambiguous use of operator>= and the alternatives are:
Mine.
The built-in operator>=(long double, int).
Now, how do I force the program to use my operator?
|
2015 update: Or, if you want to keep conversion ability using the (double)obj syntax instead the obj.to_double() syntax, make the conversion function explicit by prefixing it with that keyword. You need an explicit cast then for the conversion to trigger. Personally, I prefer the .to_double syntax, unless the conversion would be to bool because in that case the conversion is used by if(obj) even if it is explicit, and that is considerably more readable than if(obj.to_bool()) in my opinion.
Drop the conversion operator. It will cause troubles all the way. Have a function like
to_double()
Or similar that returns the double value and call that function explicitly to get a double.
For the problem at hand, there is this problem:
obj >= 10
Consider that expression. The builtin operator matches the first argument by a user defined conversion sequence for your type using the conversion operator long double(). But your function matches the second argument by a standard conversion sequence from int to long double (integral to floating point conversion). It is always ambiguous when there are conversions for two arguments, but not at least one argument that can be converted better while the remaining arguments are not converted worse for one call. In your case, the builtin one matches the second argument better but the first worse, but your function matches the first argument better but the second worse.
It's confusing, so here are some examples (conversions from char to int are called promotions, which are better than conversions from char to something other than int, which is called a conversion):
void f(int, int);
void f(long, long);
f('a', 'a');
Calls the first version. Because all arguments for the first can be converted better. Equally, the following will still call the first:
void f(int, long);
void f(long, long);
f('a', 'a');
Because the first can be converted better, and the second is not converted worse. But the following is ambiguous:
void f(char, long);
void f(int, char);
f('a', 'a'); // ambiguous
It's more interesting in this case. The first version accepts the first argument by an exact match. The second version accepts the second argument by an exact match. But both versions do not accept their other argument at least equally well. The first version requires a conversion for its second argument, while the second version requires a promotion for its argument. So, even though a promotion is better than a conversion, the call to the second version fails.
It's very similar to your case above. Even though a standard conversion sequence (converting from int/float/double to long double) is better than a user-defined conversion sequence (converting from MyClass to long double), your operator version is not chosen, because your other parameter (long double) requires a conversion from the argument which is worse than what the builtin operator needs for that argument (perfect match).
Overload resolution is a complex matter in C++, so one can impossibly remember all the subtle rules in it. But getting the rough plan is quite possible. I hope it helps you.
|
550,686
| 550,690
|
How do I convert from a 32-bit int representing time in usec to a 32-bit int representing time as a binary fraction in secs?
|
POSIX uses struct timeval to represent time intervals.
struct timeval
{
time_t tv_sec;
unsigned tv_usec;
};
GHS Integrity represents Time in the following manner,
struct Time
{
time_t Seconds;
unsigned Fraction;
};
For example, 0.5sec is represented as 0x80000000 and 0.25sec is represented as 0x40000000.
What is the best way to convert from timeval to Time?
(p.s. The answer is not to link the POSIX library into Integrity and use POSIX calls.)
|
This is an unusual way to represent time.
Anyway, there are two easy ways to do it either way if you have 64-bit integers or floating points (the former are more likely on an embedded system):
/* assuming long is 64-bit and int is 32-bit
or in general long twice the size of int: */
Fraction = (long) tv_usec * UINT_MAX / 1000000 /* usecs to fraction */
tv_usec = (long) Fraction * 1000000 / UINT_MAX /* fraction to usecs */
/* assuming floating points are available: */
Fraction = tv_usec * ((double) UINT_MAX / 1000000) /* usecs to fraction */
tv_usec = Fraction * ((double) 1000000 / UINT_MAX) /* fraction to usecs */
Obviously both are only integer approximations, because most values in one scale cannot be represented as integers in the other scale. And in one direction you may be losing some precision because the Fraction form can represent much finer times - one increment of the Fraction form is less than 0.00024 microseconds. But that is only if your timer can actually measure those values which is not very likely - most timers cannot even measure at the scale of microseconds, and the value you see in tv_usec is often rounded.
If neither 64-bit integers nor floating points are available an option, you could do it iteratively with an extra variable. I was thinking if there is a simpler (and less expensive, considering that this is timing code) way to do such scaling than doing the equivalent of iterative 64-bit multiplication and division with two 32-bit integers. Of the two ideas that came to my mind, one would not do exact even scaling and may produce results that are by up to 9 bits off, and the one that compensates for that turns out not to be any cheaper. If something new comes up in my mind I will post it here, but this is an interesting challenge. Does anyone else have a good algorithm or snippet? Perhaps with the aid of a small precomputed table?
|
550,797
| 551,247
|
Is there a better way to print a string with cout up to N characters?
|
-edit- I am sending binary and not a string. My test is using html pages so in this example i am only using a string but my question is about binary, vectors and debugging with ostream. I make this clears some confusion.
I have the following code:
cout << string(&v[0]).substr(0, len);
Is there a better way to print the string v with cout up the length len? I thought of doing v[len] = 0 but I an assertion is thrown with a size of 1. My code is:
vector<char> v;
v.reserve(1024*16); //required
v.resize(1); //so we can do &v[0]
recv(sockfd, &v[0], v.capacity(), 0);
while (l > 0)
{
cout << string(&v[0]).substr(0, l);
recv(sockfd, &v[0], v.capacity(), 0);
}
cout << "the size is " << v.size();
|
You can use the method ostream::write on the cout object:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<char> test;
test.push_back('a');
test.push_back('b');
test.push_back('c');
cout.write(&test[0], 3);
cout << endl;
}
Outputs:
abc
Since ostream::write returns an ostream& containing *this, you can even do
cout.write(&test[0], 3) << endl;
but I'm not sure that is actually any better (or clearer).
|
550,859
| 550,862
|
Reference to value of STL map element?
|
Is it OK to pass to function a reference to the value of map element, and to modify it there?
foo(string & s)
{
s = "xyz";
}
map<int, string> m;
m[1] = "abc";
foo(m[1]); // <-- Is it ok? Will m[1] be "xyz" after this call?
Thank you.
|
The answer is Yes.
(operator [] returns a reference)
|
551,069
| 551,124
|
Testing pointers for validity (C/C++)
|
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.
A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.
Update for clarification:
The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
|
Update for clarification: The problem is not with stale, freed or uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
You can't make that check. There is simply no way you can check whether a pointer is "valid". You have to trust that when people use a function that takes a pointer, those people know what they are doing. If they pass you 0x4211 as a pointer value, then you have to trust it points to address 0x4211. And if they "accidentally" hit an object, then even if you would use some scary operation system function (IsValidPtr or whatever), you would still slip into a bug and not fail fast.
Start using null pointers for signaling this kind of thing and tell the user of your library that they should not use pointers if they tend to accidentally pass invalid pointers, seriously :)
|
551,156
| 551,160
|
Compiler not creating templated ostream << operator
|
I have a class, defined in a head as:
template <typename T> class MyClass
{
template <typename U> friend std::ostream& operator<<(std::ostream& output, const MyClass<U>& p);
public:
...
}
In an implementation file, I have:
template <typename U> std::ostream& operator<<(std::ostream& output, const MyClass<U>& m)
{
output << "Some stuff";
return output;
}
Which all looks fairly kosher. However, when I try and use this operator (i.e. std::cout << MyClass()), I get the following linker error:
Undefined symbols: std::basic_ostream<char, std::char_traits<char> >& operator<< <InnerType>(std::basic_ostream<char, std::char_traits<char> >&, MyClass<InnerType> const&)
I am suprised the compiler hasn't automagicially generated this for me... Any suggestions as to what I'm doing wrong?
|
In an implementation file, I have:
That's the problem. You can't split template definitions between header and implementation files. Due to the nature of templates, C++ compilers are finicky here. Define all the code in the header to make it work.
In fact, the problem here is that all template definitions must reside within the same compilation unit because the C++ standard doesn't define how template information are shared across different units. These units are stitched together by the linker, but generics are resolved at compile time (which is earlier), not at link time.
Theoretically, the C++ standard defines a keyword, export, to handle these cases. In practice, no compiler implements this (with one exception?), and there is no intention to change this because the cost/usefulness trade-off is not considered good enough.
|
551,200
| 551,205
|
Microsoft Visual Studio (2008) - Filters in the Solution Explorer
|
In the Solution Explorer when working with C++ projects there is the standard filters of Header Files, Resource Files, and Source Files. What I'm wanting to accomplish is essentially Filters by folder.
Lets say the structure of the files was like this:
../Folder1/Source1.cpp
../Folder1/Header1.h
../Folder1/Source2.cpp
../Folder1/Header2.h
../AnotherFolder/Source1.cpp
../AnotherFolder/Header1.h
../AnotherFolder/Source2.cpp
../AnotherFolder/Header2.h
../SomeOtherSource.cpp
In the Solution Explorer, it would look like:
Header Files/Header1.h
Header Files/Header1.h
Header Files/Header2.h
Header Files/Header2.h
Source Files/SomeOtherSource.cpp
Source Files/Source1.cpp
Source Files/Source1.cpp
Source Files/Source2.cpp
Source Files/Source2.cpp
And I would like to have it look like this:
Header Files/AnotherFolder/Header1.h
Header Files/AnotherFolder/Header2.h
Header Files/Folder1/Header1.h
Header Files/Folder1/Header2.h
Source Files/AnotherFolder/Source1.cpp
Source Files/AnotherFolder/Source2.cpp
Source Files/Folder1/Source1.cpp
Source Files/Folder1/Source2.cpp
Source Files/SomeOtherSource.cpp
How would this be accomplished?
|
You are free to manually create folders yourself and move the files around. I agree this is a much more convenient way to arrange files but AFAIK there is no way to make VS do this automatically.
|
551,226
| 551,275
|
Can`t really understand what the parameters for constructing tcp::resolver::query
|
I am starting Boost.Asio and trying to make examples given on official website work.
here`s client code:
using boost::asio::ip::tcp;
int _tmain(int argc, _TCHAR* argv[])
{
try {
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], "daytime");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while(error && endpoint_iterator != end) {
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error)
throw boost::system::system_error(error);
for(;;) {
boost::array buf;
boost::system::error_code error;
std::size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; //connection closed cleanly by peer
else if (error)
throw boost::system::system_error(error);
std::cout.write(buf.data(), len);
}
}
catch(std::exception& e) {
//...
}
return 0;
}
The question is - I can not find out what the parameters would be to run program from command prompt?
|
You would run the program with the IP or Hostname of the server you want to connect to. tcp::resolver::query takes the host to resolve or the IP as the first parameter and the name of the service (as defined e.g. in /etc/services on Unix hosts) - you can also use a numeric service identifier (aka port number). It returns a list of possible endpoints, as there might be several entries for a single host.
|
551,227
| 551,533
|
Deploying application with Python or another embedded scripting language
|
I'm thinking about using Python as an embedded scripting language in a hobby project written in C++. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.
Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use?
Here's the criteria I'm weighing the different languages against:
No/Few dependencies on externally installed packages
Standard library with good feature set
Nice language :)
Doesn't result in a huge install package
edit:
I guess the question should be:
How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not?
edit2:
One more clarification. I don't need info about specifics of linking C and Python code.
|
Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function.
Py_NoSiteFlag = 1; // Disable importing site.py
Py_Initialize(); // Create a python interpreter
Put the python standard library bits you need into a zip file (called pythonXX.zip) and place this and pythonXX.dll beside the executable you distribute. Have a look at PyZipFile in the the zipfile module.
|
551,243
| 924,752
|
Symbian OS/C++ Descriptors Port?
|
Does anyone know if there's a working port of the Symbian OS C++ Descriptors functionality to other operating systems? I recall there being some code towards that here, although last time I tested it, it did not compile with G++ due to some missing/undefined types.
Thanks in advance,
Tyson
|
There's nothing inherently platform-specific about descriptors and you could trivially port them (i.e. re-compile them) to another platform from the Symbian source once it's open sourced. However, since some of the descriptor functions 'leave' you'd have to pull in the Symbian cleanup stack functionality too.
Since these are some of the worst (i.e. most non-standard and widely hated) bits of Symbian C++, I'm curious why you'd want to?
|
551,263
| 551,280
|
Method chaining + inheritance don't play well together?
|
Consider:
// member data omitted for brevity
// assume that "setAngle" needs to be implemented separately
// in Label and Image, and that Button does need to inherit
// Label, rather than, say, contain one (etc)
struct Widget {
Widget& move(Point newPos) { pos = newPos; return *this; }
};
struct Label : Widget {
Label& setText(string const& newText) { text = newText; return *this; }
Label& setAngle(double newAngle) { angle = newAngle; return *this; }
};
struct Button : Label {
Button& setAngle(double newAngle) {
backgroundImage.setAngle(newAngle);
Label::setAngle(newAngle);
return *this;
}
};
int main() {
Button btn;
// oops: Widget::setText doesn't exist
btn.move(Point(0,0)).setText("Hey");
// oops: calling Label::setAngle rather than Button::setAngle
btn.setText("Boo").setAngle(.5);
}
Any techniques to get around these problems?
Example: using template magic to make Button::move return Button& or something.
edit It has become clear that the second problem is solved by making setAngle virtual.
But the first problem remains unsolved in a reasonable fashion!
edit: Well, I guess it's impossible to do properly in C++. Thanks for the efforts anyhow.
|
For the second problem, making setAngle virtual should do the trick.
For the first one, there are no easy solutions. Widget::move returns a Widget, which doesn't have a setText method. You could make a pure virtual setText method, but that'd be a pretty ugly solution. You could overload move() on the button class, but that'd be a pain to maintain. Finally, you could probably do something with templates. Perhaps something like this:
// Define a move helper function
template <typename T>
T& move(T& obj, Point& p){ return obj.move(p); };
// And the problematic line in your code would then look like this:
move(btn, Point(0,0)).setText("Hey");
I'll let you decide which solution is cleanest. But is there any particular reason why you need to be able to chain these methods?
|
551,595
| 551,620
|
Temp file that exists only in RAM?
|
I'm trying to write an encrpytion using the OTP method. In keeping with the security theories I need the plain text documents to be stored only in memory and never ever written to a physical drive. The tmpnam command appears to be what I need, but from what I can see it saves the file on the disk and not the RAM.
Using C++ is there any (platform independent) method that allows a file to exist only in RAM? I would like to avoid using a RAM disk method if possible.
Thanks
Edit:
Thanks, its more just a learning thing for me, I'm new to encryption and just working through different methods, I don't actually plan on using many of them (esspecially OTP due to doubling the original file size because of the "pad").
If I'm totally honest, I'm a Linux user so ditching Windows wouldn't be too bad, I'm looking into using RAM disks for now as FUSE seems a bit overkill for a "learning" thing.
|
The simple answer is: no, there is no platform independent way. Even keeping the data only in memory, it will still risk being swapped out to disk by the virtual memory manager.
On Windows, you can use VirtualLock() to force the memory to stay in RAM. You can also use CryptProtectMemory() to prevent other processes from reading it.
On POSIX systems (e.g. BSD, Linux) you can use mlock() to lock memory in RAM.
|
552,131
| 552,143
|
How to read in specific sizes and store data of an unknown type in c++?
|
I'm trying to read data in from a binary file and then store in a data structure for later use. The issue is I don't want to have to identify exactly what type it is when I'm just reading it in and storing it. I just want to store the information regarding what type of data it is and how much data of this certain type there is (information easily obtained in the first couple bytes of this data)
But how can I read in just a certain amount of data, disregarding what type it is and still easily be able to cast (or something similar) that data into a readable form later?
My first idea would be to use characters, since all the data I will be looking at will be in byte units.
But if I did something like this:
ifstream fileStream;
fileStream.open("fileName.tiff", ios::binary);
//if I had to read in 4 bytes of data
char memory[4];
fileStream.read((char *)&memory, 4);
But how could I cast these 4 bytes if I later I wanted to read this and knew it was a double?
What's the best way to read in data of an unknown type but know size for later use?
fireStream.
|
You could copy it to the known data structure which makes life easier later on:
double x;
memcpy (&x,memory,sizeof(double));
or you could just refer to it as a cast value:
if (*((double*)(memory)) == 4.0) {
// blah blah blah
}
I believe a char* is the best way to read it in, since the size of a char is guaranteed to be 1 unit (not necessarily a byte, but all other data types are defined in terms of that unit, so that, if sizeof(double) == 27, you know that it will fit into a char[27]). So, if you have a known size, that's the easiest way to do it.
|
552,253
| 552,276
|
Efficient way of extracting specific numerical attributes from XML
|
The application I work uses XML for save/restore purposes. Here's an example snippet:
<?xml version="1.0" standalone="yes"?>
<itemSet>
<item handle="2" attribute1="30" attribute2="blah"></item>
<item handle="5" attribute1="27" attribute2="blahblah"></item>
</itemSet>
I want to be able to efficiently pre-process the XML which I read in from the configuration file. In particular, I want to extract the handle values from the example configuration above.
Ideally, I need a function/method to be able to pass in an opaque XML string, and return all of the handle values in a list. For the above example, a list containing 2 and 5 would be returned.
I know there's a regular expression out there that will help, but is it the most efficient way of doing this? String manipulation can be costly, and there may be potentially 1000s of XML strings I would need to process in a configuration file.
|
You are looking for a stream oriented XML parser that reads each node in your XML one at a a time rather then loading the whole thing into memory.
One of the best known is the SAX - Simple API for XML
Here's a good article describing why to use SAX and also specific of using SAX in C++.
You can think of SAX as a parser of XML that only loads the bare minimum into memory and so works well on very large XML documents. As compare to the Regex or DOM approach that will require you to load the entire document into memory.
|
552,446
| 552,451
|
Importing a C# class library into Visual C++
|
I have a C# class library that contains methods that need to be used with an external application. Unfortunately this external application only supports external APIs in C/C++.
Suppose I have a takeIntReturnDoubleArray method in this C# library that takes an integer and returns an array of doubles. All I need to do is have a C++ method that takes an integer, calls the C# library and returns an array of doubles to the calling application.
So in essence the C++ library is just acting as an intermediary between the C# wrapper and the external application.
Is there an easy way to do this? Do I have to do anything special on the C# side to allow it to be imported into C++ easily? I have seen some talk of using the #import statement but I really have no idea what I am doing when it comes to C++.
What is the approach I should be taking here?
|
You have two main options here:
C++\CLI - this allows you to have both managed and unmanaged code in the same source file. The managed portion can then call the C# code.
COM Interop - expose your .NET type as a COM interface and matching coclass which you can easily use from unmanaged C++.
|
552,509
| 552,557
|
cross compiling c++ to iphone arm
|
I've scanned over the (outdated) article that is the first hit on google about ARM cross-compiling. I've also seen the article about compiling OpenCV to the iPhone and the general cross compiling instructions there. My question is can I call the apparently already configured gcc/g++ in the iPhone developer package (which I already have installed) like in the latter article? A lot of the OpenCV stuff seems superfluous to my needs.
If I can, what would the calls look like? Should I create a Makefile to make things easier?
Also, I need -lncurses library. Can I call them like normal, or do I need to specify it's path because I'm not calling the default gcc/g++?
|
If you're using the official SDK, compiling C++ for the iPhone is as simple as including cpp files in your project and hitting "build". Of course you can still go in and tweak the compiler switches - well, most of them.
As for ncurses, I'm not sure why you'd want to use that - but the only limitation you should have is that you can't link against dynamic libraries - so you'd have to linked the object code in.
|
552,540
| 552,559
|
Why are some programs written in C++ windows-only and others are not?
|
That's something I've been wondering for a while now.
Take Notepad++ for instace. Wikipedia tells me it was written in C++ and it's Windows-only.
Now take PHP. Wikipedia tells me this is also written in C++, but that runs on other OS too.
But I see more languages then just C++ for PHP... how is this done? Do they make some new code in C++, see it works and then figure out how to do it in Perl, or what happens?
|
It depends whether you are using platform specific libraries or not. Notepad++ is a desktop application and it needs a GUI toolkit. Although there are cross-platform C++ libraries like Qt and wxWidgets, Notepad++ is probably using a Microsoft's specific technology. Thus it can't be ported in other platforms.
PHP on the other side is a WEB scripting technology so there's no need of GUI library. Also there is much more stronger interest in running PHP in many platforms than there is for Notepad++. That is an incentive for the developers to make the C++ code cross platform.
Avoid platform specific libraries isn't the only thing needed for a C++ cross platform application. It usually means coding for the least common denominator and keeping different code branches for every platform supported. Although C++ is a cross platform language, each system has its own intricacies. In fact the code could be different in the same platform as well, if a different compiler was to be used. Try downloading the C++ source of an open source application, like PHP for example. You would notice that much of the code is the same for all platforms, but there would be different bits also. Sometimes preprocessor directives are used, elsewhere totally different source files are involved.
So creating a true cross-platform C++ application is a hard job and it is usually created when there is a strong incentive to do so and many people are involved. An one-man application like Notepad++ really can't be cross-platform.
|
552,638
| 552,640
|
I've got a pointer to an object. How do I call a function that expects a reference?
|
I have a function which takes a reference to an object:
void move(Ball& ball);
I have another function calling 'move()' which has a pointer to ball:
void foo(Ball* ball){
//call move()
}
How is foo() supposed to pass ball to move()?
Should it be like:
move(*ball);
or:
move(ball);
or:
move(&ball);
|
The first one, move(*ball).
the second one, move(ball) tries to pass the pointer and the third one, move(&ball) tries to pass a pointer to a pointer.
|
552,822
| 553,647
|
Why is this code losing handles on Windows 7 Beta?
|
I'm looking for some random crashes in an old c++ application. Using sysinternals process explorer, I noticed the app losing handles, and extracted the exact situation, where the program is losing handles to a very short piece of code.
DWORD WINAPI MyTestThread( void* PThread)
{
_endthreadex(0);
return 0;
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR PParameter, int)
{
for (int i=0;i<10000;i++)
{
unsigned int threadID;
HANDLE hThread= (HANDLE)_beginthreadex( (void*)NULL, (unsigned int)32768, (unsigned int (__stdcall *)(void *))MyTestThread, (void*)NULL, (unsigned int)0, &threadID);
WaitForSingleObject((HANDLE)hThread, 1000);
CloseHandle((HANDLE)hThread);
}
return 0;
}
My problem: I can't figure out what's wrong with this code. It loses exactly 5 handles on every iteration, but it looks OK to me.
Funny thing: it seems not to lose handles on windows vista, but I'd be very surprised if this should be a bug in windows 7.
[Update] I tried using _beginthread/_endthread and CreateThread/ExitThread instead, those two are losing 5 handles, too, just like _beginthreadex.
[2nd Update] the code does run as expected. All return values are good. It is 'just' losing handles like there is no tomorrow.
[3rd Update] Big new Info The code only loses handles, if compiled with /clr! And more, if I call GC::Collect() on each iteration the handles will be reclaimed!
So, how do I find what clr-objects are being collected there?
|
Check whether some DLL which is linked to your exe is doing something strange in its DLLMain in response to DLL_THREAD_ATTACH notifications.
|
552,854
| 553,491
|
How to use a BGL directed graph as an undirected one (for use in layout algorithm)?
|
I am working on a directed graph (actually a bidirectional one) with Boost.Graph. I'd like to use the layout algorithms that exist (either Kamada-Kawai or Fruchterman-Reingold) but they only accept undirected graphs as parameters.
What is the simplest way to use these layout algorithms ?
More generally, what's the right way to lure an algorithm into thinking that a directed graph is actually undirected ?
Thanks,
Benoît
|
Are you sure that Fruchterman-Reingold algorithm only accepts undirected graphs? I tried to run the little example from the Boost documentation using a bidirectional graph instead of an undirected one, and it compiled and ran just fine.
To answer your question, I'm not sure there is any facilities built into the BGL to convert a directed graph to an undirected one. The only solution I found is creating a new graph and adding all the edges from the original one:
typedef adjacency_list<vecS, vecS, bidirectionalS> BidirectionalGraph;
typedef adjacency_list<setS, vecS, bidirectionalS> UndirectedGraph;
// UndirectedGraph uses a set to avoid parallel edges
BidirectionalGraph bdg;
// use bdg
// create an undirected graph with the edges of the first one
typedef graph_traits<BidirectionalGraph>::vertex_iterator vi_beg, vi_end;
tie(vbeg, vend) = vertices(bdg);
UndirectedGraph ug(std::distance(vbeg, vend));
typedef graph_traits<BidirectionalGraph>::edge_iterator ei, ei_end;
for (tie(ei, ei_end) = edges(bdg) ; ei != ei_end ; ++ei)
{
add_edge(source(*ei,bdg), target(*ei,bdg), ug);
}
However, I guess this solution might raise some performance issue when dealing with huge graphs. There may be a better way to achieve your goal, but I'm not an expert in BGL, so that's all I can give you :-)!
As Benoît pointed in a comment, the BGL provide a function copy_graph that copies all the vertices and edges of a graph into another one. Therefore, the code above can boil down to this:
#include <boost/graph/copy.hpp>
Bidirectional bdg;
// use bdg
// create an undirected graph with the vertices and edges of the first one
UndirectedGraph g;
copy_graph(bdg, g);
|
552,960
| 556,779
|
Disable IE script debugging via IE control
|
Bleh; Knowing how to ask the question is always the hardest so I explain a little more.
I'm using CAxWindow to create an IE window internally and passing in the URL via the string class argument:
CAxWindow wnd;
m_hwndWebBrowser = wnd.Create(m_hWnd, rect, m_URI, WS_CHILD|WS_DISABLED, 0);
It's part of an automated utility for anyone to get images from their "internal" javascript-based apps; the issue is that some people try getting images from their apps that have lots of errors; The errors fire off the IE debug window and my capture utility sits waiting for input.
Initially I thought I could disable the debugging ability via IE in windows however the process that Apache runs in and hence my App is via the SYSTEM account; not sure how I'd change the debugging options without hacking the registry.
|
I found some projects on CodeProject that does something similar...
http://www.codeproject.com/KB/shell/popupblocker.aspx?fid=15235&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=51&select=646577
http://www.codeproject.com/KB/shell/popupblocker2.aspx?df=100&forumid=15709&fr=51&select=548519#xx548519xx
And also an MSDN article regarding web browser customisation:
http://msdn.microsoft.com/en-us/library/aa770041(VS.85).aspx
I found that what I was after was two interfaces called: IOleCommandTarget and IDocHostUIHandler; I needed to override the UI handler and interpret the Script exception messages and respond with a "false" to indicate I didn't care about the error;
Unfortunately I spent waaaaay too much time getting my head back into COM and trying to get their god awful system set up that I wasn't able to finish it and after a discussion with my bos regarding spending more time trying to get this working or just disabling debug in IE; we chose the later.
3 Words; I hate COM :-p (the smilie doesn't count)
I think the path I was on would solve the issue I had and my response can contribute as an "answer"; sorry if it's not what you're looking for.
|
552,999
| 553,109
|
How to read input from a webcam in C++?
|
is it possible to read data from a generic webcam in C++ as you would from a stream object? Is there a common API or standard that works with all webcams?
I'm talking about C++ in *nix environment.
Thanks in advance.
|
For linux, V4L. AFAIR, BSD uses the same codebase. I do not know about the others...
|
553,503
| 555,180
|
Where can I find a flexible logging library for Windows Mobile?
|
Can anyone suggest any open and free library for logging on Windows Mobile application written in C++?
It would be nice if it supports logging to files, syslog (would be nice) and logging level.
|
None that I know of.
You will most likely have to look for source code available logging libraries. Windows Mobile will pretty much compile most win32 code with no or little changes, so any win32 logging library should work.
Generally I build my own as I like fine gained control over my logging code.
|
553,543
| 553,559
|
Can I have nested try-catch blocks in C++?
|
Can I have nested try-catch blocks?
For example:
void f()
{
try
{
//Some code
try
{
//Some code
}
catch(ExceptionA a)
{
//Some specific exception handling
}
//Some code
}
catch(...)
{
//Some exception handling
}
}//f
|
Yes perfectly legal.
Though it would be best to move inner ones into another method so it looks cleaner and your method(s) are smaller
|
553,682
| 553,869
|
When can I use a forward declaration?
|
I am looking for the definition of when I am allowed to do forward declaration of a class in another class's header file:
Am I allowed to do it for a base class, for a class held as a member, for a class passed to member function by reference, etc. ?
|
Put yourself in the compiler's position: when you forward declare a type, all the compiler knows is that this type exists; it knows nothing about its size, members, or methods. This is why it's called an incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.
Assuming the following forward declaration.
class X;
Here's what you can and cannot do.
What you can do with an incomplete type:
Declare a member to be a pointer or a reference to the incomplete type:
class Foo {
X *p;
X &r;
};
Declare functions or methods which accept/return incomplete types:
void f1(X);
X f2();
Define functions or methods which accept/return pointers/references to the incomplete type (but without using its members):
void f3(X*, X&) {}
X& f4() {}
X* f5() {}
What you cannot do with an incomplete type:
Use it as a base class
class Foo : X {} // compiler error!
Use it to declare a member:
class Foo {
X m; // compiler error!
};
Define functions or methods using this type
void f1(X x) {} // compiler error!
X f2() {} // compiler error!
Use its methods or fields, in fact trying to dereference a variable with incomplete type
class Foo {
X *m;
void method()
{
m->someMethod(); // compiler error!
int i = m->someField; // compiler error!
}
};
When it comes to templates, there is no absolute rule: whether you can use an incomplete type as a template parameter is dependent on the way the type is used in the template.
For instance, std::vector<T> requires its parameter to be a complete type, while boost::container::vector<T> does not. Sometimes, a complete type is required only if you use certain member functions; this is the case for std::unique_ptr<T>, for example.
A well-documented template should indicate in its documentation all the requirements of its parameters, including whether they need to be complete types or not.
|
553,846
| 553,878
|
Where is SetOaNoCache defined?
|
Attempting to disable BSTR caching:
SetOaNoCache();
VC++ compiler build output:
'SetOaNoCache': identifier not found
Don't want to use:
OANOCACHE=1
Question:
Where is SetOaNoCache defined - header file?
|
It is not defined in a header file, it is in OLEAUT32.dll. You can call it like this:
typedef int (*SETOANOCACHE)(void);
void DisableBSTRCache()
{
HINSTANCE hLib = LoadLibrary("OLEAUT32.DLL");
if (hLib != NULL)
{
SETOANOCACHE SetOaNoCache = (SETOANOCACHE)GetProcAddress(hLib, "SetOaNoCache");
if (SetOaNoCache != NULL)
SetOaNoCache();
FreeLibrary(hLib);
}
}
|
553,974
| 553,986
|
Why does (int)55 == 54 in C++?
|
So I'm learning C++. I've got my "C++ Programming Language" and "Effective C++" out and I'm running through Project Euler. Problem 1...dunzo. Problem 2...not so much. I'm working in VS2008 on a Win32 Console App.
Whats the Sum of all even terms of the Fibonacci Sequence under 4 million?
It wasn't working so I cut down to a test case of 100...
Here's what I wrote...
// Problem2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Project Euler Problem 2:\n\n";
cout << "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\n\n";
cout << "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\n\n";
cout << "Find the sum of all the even-valued terms in the sequence which do not exceed four million.\n\n";
cout << "Answer: " << Solve();
}
double Solve() {
int FibIndex = 0;
double result = 0.0;
double currentFib = GenerateNthFibonacciNumber(FibIndex);
while (currentFib < 100.0){
cout << currentFib << " " << (int)currentFib << " " << (int)currentFib % 2 << "\n";
if ((int)currentFib % 2 == 0){
result += currentFib;
cout<<(int)currentFib;
}
currentFib = GenerateNthFibonacciNumber(++FibIndex);
}
return result;
}
double GenerateNthFibonacciNumber(const int n){
//This generates the nth Fibonacci Number using Binet's Formula
const double PHI = (1.0 + sqrt(5.0)) / 2.0;
return ((pow(PHI,n)-pow(-1.0/PHI,n)) / sqrt(5.0));
}
And here's the output...
Project Euler Problem 2:
Each new term in the Fibonacci
sequence is generated by adding the
previous two terms. By starting with 1
and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued
terms in the sequence which do not
exceed four million.
0 0 0 1 1 1 1 1 1 2 2
0 3 3 1 5 5 1 8 8 0 13
13 1 21 21 1 34 34 0 55 54
0 89 89 1 Answer: 99
So I have three columns of debug code...the number returned from the generate function, (int)generatedNumber, and (int)generatedNumber % 2
So on the 11th term we have
55,54,0
Why does (int)55 = 54?
|
Casting to int truncates the number - same as if you'd called floor(currentFib). So even if currentFib is 54.999999... (a number so close to 55 that it will be rounded up when printed), (int)currentFib will produce 54.
|
554,063
| 554,134
|
How do I print a double value with full precision using cout?
|
In my earlier question I was printing a double using cout that got rounded when I wasn't expecting it. How can I make cout print a double using full precision?
|
You can set the precision directly on std::cout and use the std::fixed format specifier.
double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
You can #include <limits> to get the maximum precision of a float or double.
#include <limits>
typedef std::numeric_limits< double > dbl;
double d = 3.14159265358979;
cout.precision(dbl::max_digits10);
cout << "Pi: " << d << endl;
|
554,204
| 554,215
|
Where is Round() in C++?
|
Duplicate of: round() for float in C++
I'm using VS2008 and I've included math.h but I still can't find a round function. Does it exist?
I'm seeing a bunch of "add 0.5 and cast to int" solutions on google. Is that the best practice?
|
You may use C++11's std::round().
If you are still stuck with older standards, you may use std::floor(), which always rounds to the lower number, and std::ceil(), which always rounds to the higher number.
To get the normal rounding behaviour, you would indeed use floor(i + 0.5).
This way will give you problems with negative numbers, a workaround for that problem is by using ceil() for negative numbers:
double round(double number)
{
return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}
Another, cleaner, but more resource-intensive, way is to make use of a stringstream and the input-/output-manipulators:
#include <iostream>
#include <sstream>
double round(double val, int precision)
{
std::stringstream s;
s << std::setprecision(precision) << std::setiosflags(std::ios_base::fixed) << val;
s >> val;
return val;
}
Only use the second approach if you are not low on resources and/or need to have control over the precision.
|
554,476
| 554,575
|
Does this C++ class containing a variable size array use dynamic memory allocation?
|
Does doing something like this use dynamic memory allocation?
template <class T, int _size>
class CArray
{
public:
...
private:
T m_data[_size];
};
Can someone explain to me what's going on behind the scenes when I create the object?
CArray<SomeObject, 32> myStupidArray;
|
As mentioned in the other answers, templates are evaluated at compile time. If you're interested you can have g++ spit out the class hierarchy where you can verify its size:
template <class T, int _size>
class CArray
{
public:
private:
T m_data[_size];
};
int main(int argc, char **argv) {
CArray<int, 32> myStupidArray1;
CArray<int, 8> myStupidArray2;
CArray<int, 64> myStupidArray3;
CArray<int, 1000> myStupidArray4;
}
Compile with -fdump-class-hierarchy:
g++ -fdump-class-hierarchy blah.cc
There should be a file named blah.cc.t01.class in the current directory:
Class CArray<int, 32>
size=128 align=4
base size=128 base align=4
CArray<int, 32> (0x40be0d80) 0
Class CArray<int, 8>
size=32 align=4
base size=32 base align=4
CArray<int, 8> (0x40be0e80) 0
Class CArray<int, 64>
size=256 align=4
base size=256 base align=4
CArray<int, 64> (0x40be0f80) 0
Class CArray<int, 1000>
size=4000 align=4
base size=4000 base align=4
CArray<int, 1000> (0x40be6000) 0
|
554,551
| 623,199
|
Call function in c++ dll without header
|
I would like to call a method from an dll, but i don't have the source neither the header file. I tried to use the dumpbin /exports to see the name of the method, but i can found the methods signature?
Is there any way to call this method?
Thanks,
|
It is possible to figure out a C function signature by analysing beginnig of its disassembly. The function arguments will be on the stack and the function will do some "pops" to read them in reverse order. You will not find the argument names, but you should be able to find out their number and the types. Things may get more difficult with return value - it may be via 'eax' register or via a special pointer passed to the function as the last pseudo-argument (on the top of the stack).
|
554,646
| 577,501
|
C++ serialization of complex data using Boost
|
I have a set of classes I wish to serialize the data from. There is a lot of data though, (we're talking a std::map with up to a million or more class instances).
Not wishing to optimize my code too early, I thought I'd try a simple and clean XML implementation, so I used tinyXML to save the data out to XML, but it was just far too slow. So I've started looking at using Boost.Serialization writing and reading standard ascii or binary.
It seems to be much better suited to the task as I don't have to allocate all this memory as an overhead before I get started.
My question is essentially how to go about planning an optimal serialization strategy for a file format. I don't particularly want to serialize the whole map if it's not necessary, as it's really only the contents I'm after. Having played around with serialization a little (and looked at the output), I don't understand how loading the data back in could know when it's reached the end of the map for example, if I simply save out all the items one after another. What issues do you need to consider when planning a serialization strategy?
Thanks.
|
There are many advantages to boost.serialization. For instance, as you say, just including a method with a specified signature, allows the framework to serialize and deserialize your data. Also, boost.serialization includes serializers and readers for all the standard STL containers, so you don't have to bother if all keys have been stored (they will) or how to detect the last entry in the map when deserializing (it will be detected automatically).
There are, however, some considerations to make. For example, if you have a field in your class that it is calculated, or used to speed-up, such as indexes or hash tables, you don't have to store these, but you have to take into account that you have to reconstruct these structures from the data read from the disk.
As for the "file format" you mention, I think some times we try to focus in the format rather than in the data. I mean, the exact format of the file don't matter as long as you are able to retrieve the data seamlessly using (say) boost.serialization. If you want to share the file with other utilities that don't use serialization, that's another thing. But just for the purposes of (de)serialization, you don't have to care about the internal file format.
|
554,847
| 554,860
|
What is the best way to learn C++ if I have a bit of other programming experience?
|
Just would like some thoughts of what you think about my strategy to learn C++. While I understand that it takes years to master a programming language, I simply want to get to the point where I can be considered competent as quickly as possible. Why quickly? Well when I say quickly I'm really saying I'm committed, and that I don't want it to take forever where forever is never. If it takes five years to become competent, it takes five years. I'm not expecting 24 hours or 30 days.
About me: I don't have a CS degree, I have an anthropology degree and a Masters in library science. Learning the CS fundamentals such as Big O notation, and basics such as binary trees and linked lists, sort algorithms has been a challenge. Probably nothing substitutes a good CS degree. :( I do have many years programming experience, starting with PHP in 2001, ActionScript, 2003, JavaScript soon after. I have been writing programs in Python for about two years now and I have learned C (by reading the K&R book and writing some programs), but I'm probably not going to get hired for a C job. Also recently learned Objective C. I work as a JavaScript & Python, & CSS developer at a website at the moment.
Anyhow, this is my strategy: Read the Stroustrup book (I just started on Part I) and at the same time start a simple C++ project, while also doing many of the Stroustrup exercises.
Thoughts?
|
Bjarne's book is fantastic, especially for C++ syntax, but the one book that will really make you a competent C++ programmer is Meyers' Effective C++. Get it. Read it.
I as well do not have a CS degree, but I work for a silicon valley startup. It is possible, you just have to be aware of what's out there and never stop learning. Many students who graduate with a computer science degree end up working in a language they didn't study, so be sure to hit the fundamentals. If you hear something that's unfamiliar to you, be sure to find a good book and a coffee shop and get to it. The C++ will come in time - with Stroustrup and Meyers, you've got 90% of what it takes to be good at C++
|
555,038
| 555,651
|
Boost exception at runtime
|
Using this code:
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
using namespace std;
int main()
{
std::ofstream ofs("c:\test");
boost::archive::text_oarchive oa(ofs);
}
I'm getting an unhandled exception at runtime on executing the boost archive line:
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::archive::archive_exception> >
|
The following line is in error:
std::ofstream ofs("c:\test");
The compiler would've spit out a warning (at least) if your file was called jest; but '\t' -- being the escape for inserting a tab, your error goes by uncaught. In short, the file will not be created. You can test this with:
if (ofs.good()) { ... }
Now, since the file was not created, you don't have a valid iterator to pass on to boost::archive::text_oarchive which throws the exception.
Try this:
std::ofstream ofs("c:\\test");
// --^ (note the extra backslash)
if (ofs.good()) {
boost::archive::text_oarchive oa(ofs);
// ...
}
Hope this helps!
PS: A final nit I couldn't stop myself from making -- if you are going to use
using namespace std;
then
ofstream ofs("c:\\test");
is good enough. Of course, it is not an error to qualify ofstream, but it would not be the best coding style. But then, you know using using namespace is bad, don't you?
PPS:Thank you -- sharptooth for reminding me that \t gets you a tab!
|
555,108
| 555,113
|
Using "this" as a parameter to copy constructor
|
I have a c++ class, let's say it's called c, and I want to use the implicit copy constructor in one of the methods, like this:
c c::do_something() {
c copy = this; //I want implicit copy constructor here!
copy.something_else();
//........//
return copy;
}
However, gcc returns this error:
error: invalid conversion from 'c* const' to 'long unsigned int'
(I have another constructor from long unsigned int present)
... as if the copy constructor didn't exist. What am I doing wrong?
|
this is a pointer to an object so it should be
c copy = *this;
|
555,223
| 555,313
|
using string iterators over char* in boost regex
|
I am trying to search a char* to find matches and store each match as a struct using boost regex. I do not know how to use the std::string iterators over char*. So I created std::string from char* and using them. But now I want pointers in the original char* which can only be found using std::string I created. See the following code. The comments should clear your doubts.
typedef struct {
void *pFind; // Pointer to begining of match
int lenFind; // Length of match
} IppRegExpFind;
bool regExSearch(int nStrLen /*Length of input string*/,
std::vector<IppRegExpFind>& vectResult /*vector of struct to store matches*/,
int &numMatches /* number of matches*/,
const char *sStrInput /*Input string to be searched*/,
const char *sStrRegex /*Input regex string*/)
{
bool bStatusOk = true;
try{
std::string regexStr(sStrRegex);
std::string inputStr(sStrInput);
static const boost::regex ex(regexStr);
std::string::const_iterator start, end;
start = inputStr.begin();
end = inputStr.end();
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
std::vector <std::string> matches;
while(boost::regex_search(start, end, what, ex, flags))
{
matches.push_back(what.str());
start = what[0].second;
}
// convert boost:match_Results to a vector of IppRegExpFind
}
catch(...){
bStatusOk = false;
}
return bStatusOk;
}
|
You can get the original pointer by
sStrInput+what.position(0)
I'm not sure, however, why do you need all the tricks with std::string. According to the documentation, boost::regex_search can search any range specified by bidirectional iterators (ie. char* is a bidirectional iterator, so you pass (str, str+strlen(str)) as start and end), and there are even overloads for char* that treat it as C string.
|
555,292
| 555,305
|
Thread communication theory
|
What is the common theory behind thread communication? I have some primitive idea about how it should work but something doesn't settle well with me. Is there a way of doing it with interrupts?
|
Really, it's just the same as any concurrency problem: you've got multiple threads of control, and it's indeterminate which statements on which threads get executed when. That means there are a large number of POTENTIAL execution paths through the program, and your program must be correct under all of them.
In general the place where trouble can occur is when state is shared among the threads (aka "lightweight processes" in the old days.) That happens when there are shared memory areas,
To ensure correctness, what you need to do is ensure that these data areas get updated in a way that can't cause errors. To do this, you need to identify "critical sections" of the program, where sequential operation must be guaranteed. Those can be as little as a single instruction or line of code; if the language and architecture ensure that these are atomic, that is, can't be interrupted, then you're golden.
Otherwise, you idnetify that section, and put some kind of guards onto it. The classic way is to use a semaphore, which is an atomic statement that only allows one thread of control past at a time. These were invented by Edsgar Dijkstra, and so have names that come from the Dutch, P and V. When you come to a P, only one thread can proceed; all other threads are queued and waiting until the executing thread comes to the associated V operation.
Because these primitives are a little primitive, and because the Dutch names aren't very intuitive, there have been some ther larger-scale approaches developed.
Per Brinch-Hansen invented the monitor, which is basically just a data structure that has operations which are guaranteed atomic; they can be implemented with semaphores. Monitors are pretty much what Java synchronized statements are based on; they make an object or code block have that particular behavir -- that is, only one thread can be "in" them at a time -- with simpler syntax.
There are other modeals possible. Haskell and Erlang solve the problem by being functional languages that never allow a variable to be modified once it's created; this means they naturally don't need to wory about synchronization. Some new languages, like Clojure, instead have a structure called "transactional memory", which basically means that when there is an assignment, you're guaranteed the assignment is atomic and reversible.
So that's it in a nutshell. To really learn about it, the best places to look at Operating Systems texts, like, eg, Andy Tannenbaum's text.
|
555,327
| 555,357
|
Check for valid image
|
I'm writing a program that downloads information from the web and part of that is images.
At the moment I'm having a problem as the code to download the images is a different part to the code that displays them (under mvc). If a 404 is issued or the image download fails some way the display code pops a message propmt up which i would like to avoid.
Is there an easy way to check to see if an image is valid? I'm only concerned about jpg, gif and png.
Note: I dont care about reading the image data, just to check to see if it is valid image format.
|
Do you want to check whether the download would be successful? Or do you want to check that what is downloaded is, in fact, an image?
In the former case, the only way to check is to try to access it and see what kind of HTTP response code you get. You can send an HTTP HEAD request to get the response code without actually downloading the image, but if you're just going to go ahead and download the image anyway (if it's successful) then sending a separate HEAD request seems like a waste of time (and bandwidth).
Alternatively, if you really want to check that what you're downloading is a valid image file, you have to read the whole file to check it for corruption. But if you just want to check that the file extension is accurate, it should be enough to check the first few bytes of the file. All GIF images start with the ASCII text GIF87 or GIF89 depending on which GIF specification is used. PNG images start with the ASCII text PNG, and JPEG images have some magic number, which appears to be 0xd8ffe0ff based on the JPEGs I looked at. (You should do some research and check that, try Wikipedia for links) Keep in mind, though, that to get even the first few bytes of the image, you will need to send an HTTP request which could return a 404 (and in that case you don't have any image to check).
|
555,505
| 555,524
|
When were the 'and' and 'or' alternative tokens introduced in C++?
|
I've just read this nice piece from Reddit.
They mention and and or being "Alternative Tokens" to && and ||
I was really unaware of these until now. Of course, everybody knows about the di-graphs and tri-graphs, but and and or? Since when? Is this a recent addition to the standard?
I've just checked it with Visual C++ 2008 and it doesn't seem to recognize these as anything other than a syntax error. What's going on?
|
MSVC supports them as keywords only if you use the /Za option to disable extensions; this is true from at least VC7.1 (VS2003).
You can get them supported as macros by including iso646.h.
My guess is they believe that making them keywords by default would break too much existing code (and I wouldn't be surprised if they are right).
|
555,612
| 555,665
|
Constructor doesn't work for class inherited from std::string
|
when doing
#include <string>
class MyString : public std::string
{
public:
MyString() {}
};
But the usage below:
MyString s = "Happy day";
MyString s("Happy Day");
MyString s = (MyString)"Happy day";
neither of them works.
It seems that there's something to do with constructors/operators declaration/overridding, but can anyone help point out where may I find these resources?
Thanks.
|
You need to define some constructors for the different types that you want to be able to convert into your strings. These constructors can basically just hand the parameters through to the underlying std::string.
If you don't manually create them, the compiler creates a default- and a copy-constructor for you:
MyString() : std::string() { }
MyString(const MyString &other) : std::string(other) { }
To allow construction from string literals, you need a constructor that takes a const char*:
MyString(const char* other) : std::string(other) { }
A constructor that takes a const std::string& would also be useful to convert std::strings to your string type. If you want to avoid implicit conversions of normal strings, you should make it explicit:
explicit MyString(const std::string &other) : std::string(other) { }
(Edited because my original version was full of errors and I can't delete the accepted answer)
|
555,681
| 555,688
|
nested classes and references to outside classes (c++)
|
This is quite straightforward - gcc fails to to compile this sample code (c++).
class myclass {
struct mystruct {
myclass something;
int something_else;
};
};
It tells me, that
Field 'something' has incomplete type.
I probably miss something trivial, because I'm quite new in c++, but why can't I make nested class/struct with references to outside class?
|
You can't put an object into itself. Perhaps you wanted a pointer to myclass.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.