 |
 |
|
 |
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Warp <war### [at] tag povray org> wrote:
> class PrivateClass;
> class MyClass
> {
> std::shared_ptr<PrivateClass> privateObject;
> };
Oh, and take into account that if instances of MyClass are copied around,
the copies will share the one and same PrivateClass object. That will not
get deep-copied. (That's what the "shared ptr" means, actually.)
If you want to avoid MyClass being copied around, that can be disabled.
(Of course this restricts the ways in which the class can be used, so
it's always a compromise.)
Another possibility is to write a copy constructor and a copy assignment
operator that deep-copies the private object... It all depends on how
exactly you need MyClass to behave.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> class PrivateClass;
>
>> class MyClass
>> {
>> std::shared_ptr<PrivateClass> privateObject;
>> };
OK. That seems easy enough.
> Oh, and take into account that if instances of MyClass are copied around,
> the copies will share the one and same PrivateClass object. That will not
> get deep-copied. (That's what the "shared ptr" means, actually.)
There "should" only ever be one instance of this class; I'd just like to
avoid the program exploding if somebody *does* copy that instance for
some reason. A shallow copy is acceptable.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
> There "should" only ever be one instance of this class; I'd just like to
> avoid the program exploding if somebody *does* copy that instance for
> some reason. A shallow copy is acceptable.
Is there a C++ equivalent to the C# static class? That would ensure at
compile-time that nobody tried to create an(other) instance.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
scott <sco### [at] scott com> wrote:
> > There "should" only ever be one instance of this class; I'd just like to
> > avoid the program exploding if somebody *does* copy that instance for
> > some reason. A shallow copy is acceptable.
> Is there a C++ equivalent to the C# static class? That would ensure at
> compile-time that nobody tried to create an(other) instance.
You could use a namespace instead of a class. Private implementation can
then all go to the source file, away from the header file.
On the other hand, this limits where you can use this "pseudoclass" and
it could be difficult to maintain backwards compatibility if you ever
wanted to change it so that more than one instance could be created.
Of course you could have a class that only has static member functions...
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Le 16/05/2013 17:27, Warp nous fit lire :
> scott <sco### [at] scott com> wrote:
>> Is there a C++ equivalent to the C# static class? That would ensure at
>> compile-time that nobody tried to create an(other) instance.
>
You can either have all methods of a class static, or use a singleton
pattern.
> You could use a namespace instead of a class. Private implementation can
> then all go to the source file, away from the header file.
>
> On the other hand, this limits where you can use this "pseudoclass" and
> it could be difficult to maintain backwards compatibility if you ever
> wanted to change it so that more than one instance could be created.
>
> Of course you could have a class that only has static member functions...
>
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 14/05/2013 06:29 PM, Orchid Win7 v1 wrote:
> But that's nothing compared to how long it took to get VS to produce a
> DLL, and then get C# to successfully call this DLL without access
> violations... >_<
But THAT is nothing compared to the trouble we had trying to build a
Linux "shared object" and getting Mono to load that...
I can still hardly believe that this whole improbable contraption
actually ended up WORKING in the end! o_O
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Le_Forgeron <jgr### [at] free fr> wrote:
> You can either have all methods of a class static, or use a singleton
> pattern.
If you are using an enforced singleton, and you don't want to expose
*any* implementation detail to the outside, one possibility would be
to do this:
//------------------------------------------------------------
// In the header file:
// ------------------
class TheClass
{
public:
virtual void someFunction() = 0;
virtual int anotherFunction(int parameter) = 0;
virtual void aThirdFunction(double, double) = 0;
};
TheClass& theClassInstance();
//------------------------------------------------------------
//------------------------------------------------------------
// In the implementation file:
// --------------------------
#include "TheClass.hh"
namespace
{
class TheActualClass: public TheClass
{
struct InnerType { int a, b; }
int privateMember;
double anotherPrivateMember;
InnerType aThirdPrivateMember;
void privateFunction();
public:
TheActualClass() { /* constructor */ }
virtual void someFunction()
{
// implement it here
}
virtual int anotherFunction(int parameter)
{
// implement it here
}
virtual void aThirdFunction(double, double)
{
// implement it here
}
};
}
TheClass& theClassInstance()
{
static TheActualClass actualClassInstance;
return actualClassInstance;
}
//------------------------------------------------------------
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 16/05/2013 08:39 AM, Orchid Win7 v1 wrote:
>>> class PrivateClass;
>>
>>> class MyClass
>>> {
>>> std::shared_ptr<PrivateClass> privateObject;
>>> };
>
> OK. That seems easy enough.
I entered this into VisualStudio, and it worked great.
However, when I tried to compile it under Linux, GCC refused to accept it.
First, VS seems to somehow allow you to compile things even without
actually importing the necessary include files. (E.g., it will happily
accept std::shared_ptr even though I didn't #include <memory>.) GCC
demands that you actually specify the include files [like you'd expect].
Weird, but true.
Second, it seems this "feature" only exists in C++11. I don't know what
GCC is defaulting to, but apparently you have to add a switch to tell it
to accept C++11. And when I do that, my code compiles perfectly, but the
rest of the codebase breaks spectacularly.
So, in summary, I had to revert everything back to how it was. *sigh*
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 16/05/2013 06:46 PM, Orchid Win7 v1 wrote:
> I can still hardly believe that this whole improbable contraption
> actually ended up WORKING in the end! o_O
The daft thing is, it turns out to actually be pretty easy to write some
C++, make a DLL out of it, and call that from C#. The actual code that
ended up in source control is both small and simple.
This belies the vast amount of man-hours it took to *arrive* at this
final arrangement. It took an absurd amount of Google searches and
trail-and-error to get the myriad of pieces to fit together just right.
In summary, it's easy when you know how. So easy, presumably, that
nobody bothers to write down how it's actually done - so the next person
who tries to do this will have the exact same problem. :-/
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> Second, it seems this "feature" only exists in C++11. I don't know what
> GCC is defaulting to, but apparently you have to add a switch to tell it
> to accept C++11. And when I do that, my code compiles perfectly, but the
> rest of the codebase breaks spectacularly.
> So, in summary, I had to revert everything back to how it was. *sigh*
You could use std::auto_ptr instead of std::shared_ptr, but then you'd
better disable copying for your class.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/17/2013 11:16 AM, Warp wrote:
> Orchid Win7 v1 <voi### [at] dev null> wrote:
>> Second, it seems this "feature" only exists in C++11. I don't know what
>> GCC is defaulting to, but apparently you have to add a switch to tell it
>> to accept C++11. And when I do that, my code compiles perfectly, but the
>> rest of the codebase breaks spectacularly.
>
>> So, in summary, I had to revert everything back to how it was. *sigh*
>
> You could use std::auto_ptr instead of std::shared_ptr, but then you'd
> better disable copying for your class.
>
Or use boost::shared_ptr of course.
Actually, this reminds me that I should update some of my own code from
boost:shared_ptr to std::shared_ptr.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 15/05/2013 10:44 PM, Warp wrote:
> Orchid Win7 v1<voi### [at] dev null> wrote:
>> So I have to put the entire class definition into the header file. But
>> that means I have to put Secrets into the header file too - a data
>> structure that clients have absolutely no reason to know anything about.
>
> If having the internal-implementation-detail as a member variable of
> the class is something you just must avoid, and especially if this is
> a class that doesn't get instantiated a lot, then the solution is to
> use the Pimpl idiom, which regardless of the funny name, is exactly what
> you described. In other words, make a forward declaration of that private
> class and just have a pointer to it as member.
My next question was going to be "is there a way to expose part of a
class so that the test framework can access it, but nothing else can?"
And then I read the documentation for our test framework [GTest, in case
anybody cares], and it says to do basically the same thing as the above.
IOW, make a private class, put it in its own header file, let the test
framework include that header file, but nobody else.
Not sure if it's worth it just to hide one single method, but it might
be useful in other parts of the codebase...
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> And then I read the documentation for our test framework [GTest, in case
> anybody cares], and it says to do basically the same thing as the above.
> IOW, make a private class, put it in its own header file, let the test
> framework include that header file, but nobody else.
In principle if a class or function exists in a namespace that's not
local to a compilation unit (in other words, a nameless namespace inside
a compilation unit), it will be visible globally and could therefore
technically speaking be used by everything else.
Unlike it might seem, header files in C/C++ are not a language feature.
They are not syntax that imposes some kind of semantics (eg. access
restrictions or something like that.) It's not like other code couldn't
use some class or function if it doesn't have access to the header file
that declares them.
Header files are both a convenience and an abstraction tool, but are
strictly speaking unnecessary.
Let's say that you *know* that somewhere in the innards of some compilation
unit (which might be eg. a library) there's a function named 'foo' which
takes an int and returns an int, which is in the global namespace. Even
if you have no access to any header that declares said function, you can
still just write in your own code:
//----------------------------------------------------------------
int foo(int);
void myFunction()
{
foo(5);
}
//----------------------------------------------------------------
With classes it becomes a bit more complicated because you need to
know the exact contents of the class. However, technically speaking
if you know that you don't need any header file to use it.
Of course all this is mostly theoretical.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>>> So, in summary, I had to revert everything back to how it was. *sigh*
>>
>> You could use std::auto_ptr instead of std::shared_ptr, but then you'd
>> better disable copying for your class.
>
> Or use boost::shared_ptr of course.
OK, so I went with boost::shared_ptr in the end.
However, I can't seem to figure out what to write in the constructor.
I've got a field that looks like
boost::shared_ptr<std::vector<Foo>> _foo;
What do I need to do to initialise this correctly?
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 20/05/2013 09:15 PM, Warp wrote:
> Of course all this is mostly theoretical.
Yeah. Assuming that my fellow coders aren't *purposely* trying to break
things, I just want to structure the code I'm writing in a way which
minimises the potential for mistakes, that's all.
(We've got some code which is only public so that the test suite can
run. It makes me feel slightly twitchy, but hey...)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/21/2013 10:25 AM, Orchid Win7 v1 wrote:
> However, I can't seem to figure out what to write in the constructor.
> I've got a field that looks like
>
> boost::shared_ptr<std::vector<Foo>> _foo;
>
> What do I need to do to initialise this correctly?
boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
Take a look over the constructors of shared_ptr for more detail. I
should note that it's relatively uncommon that I want a shared_ptr to a
std::vector. Unless you actually need to store _foo somewhere else in
the code it's might be better to just forgo the shared_ptr and pass _foo
by reference to whichever functions need it.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/21/2013 10:32 AM, Kevin Wampler wrote:
> On 5/21/2013 10:25 AM, Orchid Win7 v1 wrote:
>> However, I can't seem to figure out what to write in the constructor.
>> I've got a field that looks like
>>
>> boost::shared_ptr<std::vector<Foo>> _foo;
>>
>> What do I need to do to initialise this correctly?
>
>
> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>
Oh, and it's probably best to write it like this:
boost::shared_ptr<std::vector<Foo> > _foo(new std::vector<Foo>());
Since some compilers will complain about using >> in a type definition
(due to the ambiguity with the >> operator).
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 21/05/2013 06:32 PM, Kevin Wampler wrote:
> On 5/21/2013 10:25 AM, Orchid Win7 v1 wrote:
>> However, I can't seem to figure out what to write in the constructor.
>> I've got a field that looks like
>>
>> boost::shared_ptr<std::vector<Foo>> _foo;
>>
>> What do I need to do to initialise this correctly?
>
>
> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>
> Take a look over the constructors of shared_ptr for more detail. I
> should note that it's relatively uncommon that I want a shared_ptr to a
> std::vector. Unless you actually need to store _foo somewhere else in
> the code it's might be better to just forgo the shared_ptr and pass _foo
> by reference to whichever functions need it.
The only reason I'm doing this is to avoid putting the real definition
of Foo in the header file.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> However, I can't seem to figure out what to write in the constructor.
> I've got a field that looks like
> boost::shared_ptr<std::vector<Foo>> _foo;
> What do I need to do to initialise this correctly?
What do you mean by "field"? Your question is not clear enough.
(And btw, don't start names with an underscore. Those are reserved for
the compiler.)
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 22/05/2013 08:45 PM, Warp wrote:
> Orchid Win7 v1<voi### [at] dev null> wrote:
>> However, I can't seem to figure out what to write in the constructor.
>> I've got a field that looks like
>
>> boost::shared_ptr<std::vector<Foo>> _foo;
>
>> What do I need to do to initialise this correctly?
>
> What do you mean by "field"? Your question is not clear enough.
I mean something like
class Foobar
{
private:
boost::shared_ptr<std::vector<Foo>> foo;
public:
Foobar()
}
> (And btw, don't start names with an underscore. Those are reserved for
> the compiler.)
Hoooookay... In that case, there's about 200 lines in the existing
codebase that need to be changed. o_O
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>
> Oh, and it's probably best to write it like this:
>
> boost::shared_ptr<std::vector<Foo> > _foo(new std::vector<Foo>());
>
> Since some compilers will complain about using >> in a type definition
> (due to the ambiguity with the >> operator).
VisualStudio compiles this perfectly. GCC point-blank fails to compile
it. *sigh* Gotta love the number of inconsistencies between two
compilers for supposedly "the same" language...
(VC emits endless warnings about "printf may be unsafe; please use
printf_s instead". Apparently the latter function doesn't exist in GCC...)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Le 2013-05-23 03:22, Orchid Win7 v1 a écrit :
>>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>>
>> Oh, and it's probably best to write it like this:
>>
>> boost::shared_ptr<std::vector<Foo> > _foo(new std::vector<Foo>());
>>
>> Since some compilers will complain about using >> in a type definition
>> (due to the ambiguity with the >> operator).
>
> VisualStudio compiles this perfectly. GCC point-blank fails to compile
> it. *sigh* Gotta love the number of inconsistencies between two
> compilers for supposedly "the same" language...
You are surprised that a Microsoft product allows something that is
frowned upon by a more anal-retentive competitor?!?
>
> (VC emits endless warnings about "printf may be unsafe; please use
> printf_s instead". Apparently the latter function doesn't exist in GCC...)
They are MS-specific versions of the functions.
http://msdn.microsoft.com/en-us/library/8ef0s5kh%28v=vs.80%29.aspx
http://msdn.microsoft.com/en-us/library/239ffwa0%28v=vs.80%29.aspx
I'm sure the purists would frown that Microsoft decides to mess with
<sdtio.h> instead of putting them in a "msstdio.h" or similar. Way back
when the dinosaurs still roamed the Earth, I used to hang in comp.lang.c
and I vividly remember certain members being quite angry at Borland for
pretending that conio.h was part of the standard headers and its
functions part of the standard libraries.
--
/*Francois Labreque*/#local a=x+y;#local b=x+a;#local c=a+b;#macro P(F//
/* flabreque */L)polygon{5,F,F+z,L+z,L,F pigment{rgb 9}}#end union
/* @ */{P(0,a)P(a,b)P(b,c)P(2*a,2*b)P(2*b,b+c)P(b+c,<2,3>)
/* gmail.com */}camera{orthographic location<6,1.25,-6>look_at a }
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/23/2013 6:27 AM, Francois Labreque wrote:
> Le 2013-05-23 03:22, Orchid Win7 v1 a écrit :
>>>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>>>
>>> Oh, and it's probably best to write it like this:
>>>
>>> boost::shared_ptr<std::vector<Foo> > _foo(new std::vector<Foo>());
>>>
>>> Since some compilers will complain about using >> in a type definition
>>> (due to the ambiguity with the >> operator).
>>
>> VisualStudio compiles this perfectly. GCC point-blank fails to compile
>> it. *sigh* Gotta love the number of inconsistencies between two
>> compilers for supposedly "the same" language...
>
> You are surprised that a Microsoft product allows something that is
> frowned upon by a more anal-retentive competitor?!?
>
Actually, I'm a little surprised that GCC didn't accept it, as that sort
of things should be allowed under the C++11 standard
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html) and
GCC 4.7 is listed as supporting that feature
(http://gcc.gnu.org/gcc-4.7/cxx0x_status.html). In general GCC seems to
have much better C++11 support that MSVC, so it's strange to see an
example of the opposite -- perhaps Andrew's using an old version of GCC
or something.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>>> boost::shared_ptr<std::vector<Foo> > _foo(new std::vector<Foo>());
>>>
>>> Since some compilers will complain about using >> in a type definition
>>> (due to the ambiguity with the >> operator).
>>
>> VisualStudio compiles this perfectly. GCC point-blank fails to compile
>> it. *sigh* Gotta love the number of inconsistencies between two
>> compilers for supposedly "the same" language...
>
> You are surprised that a Microsoft product allows something that is
> frowned upon by a more anal-retentive competitor?!?
boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
I don't see how the >> is ambiguous at all in this statement. Seems to
me like lazy/bad parser design if this trips it up.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/23/2013 7:14 AM, scott wrote:
>
> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>
> I don't see how the >> is ambiguous at all in this statement. Seems to
> me like lazy/bad parser design if this trips it up.
>
It's not quite so cut and dry as you might guess. For example:
#include <iostream>
using std::cout;
using std::endl;
int _foo(int i) {
return i;
}
namespace std {
static const int vector = 7;
}
namespace boost {
static const int shared_ptr = 5;
}
int main(int argc, char** argv) {
int Foo = 3;
cout << (boost::shared_ptr<std::vector<Foo>> _foo(NULL)) << endl;
return 0;
}
If you run this program it should print "1" (at least in MSVC), which is
the result of treating < and >> and the less-than and bit-shift
operators. Of course you couldn't write "new std::vector<Foo>()" in
this scheme, but it does show that it's hard to tell what's a template
and what's not at a purely syntatic level.
In any case, the C++11 standard does allow
"boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>()); " and
the most recent version of GCC supposedly supports this. You can read a
bit more about it here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> > What do you mean by "field"? Your question is not clear enough.
> I mean something like
> class Foobar
> {
> private:
> boost::shared_ptr<std::vector<Foo>> foo;
> public:
> Foobar()
> }
Why didn't you say so in the first place?
If you want to initialize that member function in the constructor, use
the constructor's initializer list or just assign to it in the contructor's
body. In the first case:
Foobar::Foobar(): foo(new std::vector<Foo>)
{}
Or if you prefer,
Foobar::Foobar()
{
foo = new std::vector<Foo>;
}
Btw, C++98 does not support >> for closing a double template. You have
to add a space in between.
I'm wondering why you are using a std::vector, though. I thought that what
you wanted was something like this:
//----------------------------------------------------------------
class Foobar
{
struct Impl;
boost::shared_ptr<Impl> impl;
public:
Foobar();
};
//----------------------------------------------------------------
In which case the implementation would be like:
//----------------------------------------------------------------
struct Foobar::Impl
{
std::vector<Foo> array;
}
Foobar::Foobar(): impl(new Impl)
{}
//----------------------------------------------------------------
Much simpler and cleaner that way.
> > (And btw, don't start names with an underscore. Those are reserved for
> > the compiler.)
> Hoooookay... In that case, there's about 200 lines in the existing
> codebase that need to be changed. o_O
I have never quite understood why so many programmers seem to be obsessed
with putting underscores at the beginning of names.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Kevin Wampler <nob### [at] nowhere net> wrote:
> On 5/21/2013 10:25 AM, Orchid Win7 v1 wrote:
> > However, I can't seem to figure out what to write in the constructor.
> > I've got a field that looks like
> >
> > boost::shared_ptr<std::vector<Foo>> _foo;
> >
> > What do I need to do to initialise this correctly?
> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
*Where* are you doing that?
If you mean it like this:
class Foobar
{
boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
};
then it works, but only in C++11. I think Andrew needed to do it in C++98.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>>
>> I don't see how the >> is ambiguous at all in this statement. Seems to
>> me like lazy/bad parser design if this trips it up.
>
> It's not quite so cut and dry as you might guess. For example:
...
> cout << (boost::shared_ptr<std::vector<Foo>> _foo(NULL)) << endl;
Is that ambiguous?
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/23/2013 8:58 AM, scott wrote:
>>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>>>
>>> I don't see how the >> is ambiguous at all in this statement. Seems to
>>> me like lazy/bad parser design if this trips it up.
>>
>> It's not quite so cut and dry as you might guess. For example:
> ...
>> cout << (boost::shared_ptr<std::vector<Foo>> _foo(NULL)) << endl;
>
> Is that ambiguous?
>
Obviously not since it compiles. It is, however, ambiguous unless you
know the types of boost::shared_ptr and std::vector (and you need to
know them during lexical analysis). I wasn't saying that it's
impossible to correctly parse this sort of thing, just that correctly
parsing it is a more non-trivial task than it might at first appear.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/23/2013 8:41 AM, Warp wrote:
> Kevin Wampler <nob### [at] nowhere net> wrote:
>> On 5/21/2013 10:25 AM, Orchid Win7 v1 wrote:
>>> However, I can't seem to figure out what to write in the constructor.
>>> I've got a field that looks like
>>>
>>> boost::shared_ptr<std::vector<Foo>> _foo;
>>>
>>> What do I need to do to initialise this correctly?
>
>> boost::shared_ptr<std::vector<Foo>> _foo(new std::vector<Foo>());
>
> *Where* are you doing that?
>
I was just giving him an example to point out that you pass a raw
pointer to the constructor of shared_ptr and assuming that he'd figure
the rest out from there. But you're right that I perhaps should have
been more explicit.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> You are surprised that a Microsoft product allows something that is
>> frowned upon by a more anal-retentive competitor?!?
>>
>
> Actually, I'm a little surprised that GCC didn't accept it, as that sort
> of things should be allowed under the C++11 standard
> (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html) and
> GCC 4.7 is listed as supporting that feature
> (http://gcc.gnu.org/gcc-4.7/cxx0x_status.html). In general GCC seems to
> have much better C++11 support that MSVC, so it's strange to see an
> example of the opposite -- perhaps Andrew's using an old version of GCC
> or something.
[Our version of] GCC seems to require a command-line switch to enable
C++11 support, so...
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 23/05/2013 04:38 PM, Warp wrote:
> Orchid Win7 v1<voi### [at] dev null> wrote:
>>> What do you mean by "field"? Your question is not clear enough.
>
>> I mean something like
>
>> class Foobar
>> {
>> private:
>> boost::shared_ptr<std::vector<Foo>> foo;
>> public:
>> Foobar()
>> }
>
> Why didn't you say so in the first place?
>
> If you want to initialize that member function in the constructor, use
> the constructor's initializer list or just assign to it in the contructor's
> body. In the first case:
>
> Foobar::Foobar(): foo(new std::vector<Foo>)
> {}
>
> Or if you prefer,
>
> Foobar::Foobar()
> {
> foo = new std::vector<Foo>;
> }
I had hoped it would "just work" the same way it does if it wasn't a
pointer. But it appears that no, you have to make it actually point to
something. (Which is reasonable.) The constructor seems like the most
sensible place to do that.
> Btw, C++98 does not support>> for closing a double template. You have
> to add a space in between.
Yeah, I already discovered that. ;-)
> I'm wondering why you are using a std::vector, though. I thought that what
> you wanted was something like this:
>
> //----------------------------------------------------------------
>
> class Foobar
> {
> struct Impl;
> boost::shared_ptr<Impl> impl;
>
> public:
> Foobar();
> };
> //----------------------------------------------------------------
>
> In which case the implementation would be like:
>
> //----------------------------------------------------------------
> struct Foobar::Impl
> {
> std::vector<Foo> array;
> }
>
> Foobar::Foobar(): impl(new Impl)
> {}
> //----------------------------------------------------------------
>
> Much simpler and cleaner that way.
Ooo, interesting... Yeah, that could work.
>>> (And btw, don't start names with an underscore. Those are reserved for
>>> the compiler.)
>
>> Hoooookay... In that case, there's about 200 lines in the existing
>> codebase that need to be changed. o_O
>
> I have never quite understood why so many programmers seem to be obsessed
> with putting underscores at the beginning of names.
Apparently ReSharper insists that every C# private field begins with an
underscore. I guess when the guys started writing C++, they just copied
that naming convention. After all, it's only a name, right? You can name
your stuff anything you li- oh, OK, maybe not...
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Today, I spent about 2 hours trying to figure out why the hell all the
tests pass when I compile in Debug mode, but two of them fail if I
compile in Release mode.
Literally, every time I run in Debug mode, all the tests pass. It only
fails in Release mode. In particular, that means I can't fire up the
debugger to see why it's failing. You can only debug in Debug mode, and
in Debug mode it works perfectly.
Apparently Google is your friend. After some minimal amount of effort, I
came across a very well-written forum post which helpfully explains that
in Debug mode all variables are guaranteed to be initialised to default
values, whereas in Release mode variables take on whatever random
gibberish happens to be in memory, unless you remember to explicitly
initialise them to something sane.
Ouch. >_<
Now I guess I understand why Java, C#, et al make such a fuss about
insisting on explicit initialisation and / or explicitly specifying
default initialisation rules...
The other fun thing is that C++ allows you to "throw" absolutely
anything. Several places in the code throw std::string, presumably in
the hope that this will result in some helpful error message being printed.
It doesn't. ;-)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
> [Our version of] GCC seems to require a command-line switch to enable
> C++11 support, so...
In other news, I may have found out why turning this on breaks GTest.
Apparently it's somehow related to a late change to the C++11 spec.
Basically VC doesn't support some feature that got added to the standard
late. (Varadic tuples or something.) That doesn't completely explain why
it compiles just fine without C++11 turned on though...
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
The OTHER fun thing, of course, is when you invoke a template with the
wrong parameters.
Trouble is, the compiler has no idea that the parameters are wrong. All
it knows is that when it tries to expand the template, somewhere several
million miles away from your code a type mismatch happens, or an
operator doesn't exist, or...
This would be acceptable if VC offered some how to find out WHAT
TEMPLATE it was attempting to expand when the error occurred. But no, it
just shows you the source code for the STL (or Boost or whatever) and
points at the line on which the problem was actually detected. There
seems to be no way that I can discover what line of which file resulting
in this template being invoked in the first place - and THAT is surely
where the problem is, not in STL itself.
(E.g., today I erroneously said set<string, string>. It took quite a
while to hunt through the source control history to manually inspect
every template instruction I've recently touched and thus discover the
problem. If I knew, say, WHAT FILE to look in, it might be faster...)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Le 23/05/2013 19:33, Orchid Win7 v1 a écrit :
> Today, I spent about 2 hours trying to figure out why the hell all the
> tests pass when I compile in Debug mode, but two of them fail if I
> compile in Release mode.
>
> Literally, every time I run in Debug mode, all the tests pass. It only
> fails in Release mode. In particular, that means I can't fire up the
> debugger to see why it's failing. You can only debug in Debug mode, and
> in Debug mode it works perfectly.
>
> Apparently Google is your friend. After some minimal amount of effort, I
> came across a very well-written forum post which helpfully explains that
> in Debug mode all variables are guaranteed to be initialised to default
> values, whereas in Release mode variables take on whatever random
> gibberish happens to be in memory, unless you remember to explicitly
> initialise them to something sane.
>
> Ouch. >_<
>
That's why options like -Wall -Wextra -pedantic -Wold-style-cast are my
friends with g++.
I do not know MSVC enough, but it might have that kind of warnings too
(on explicit demand, of course)
> Now I guess I understand why Java, C#, et al make such a fuss about
> insisting on explicit initialisation and / or explicitly specifying
> default initialisation rules...
>
>
>
> The other fun thing is that C++ allows you to "throw" absolutely
> anything. Several places in the code throw std::string, presumably in
> the hope that this will result in some helpful error message being printed.
>
> It doesn't. ;-)
with gdb, "catch throw" is wonderful before "run" in such cases.
Now, someone need to have an exploration of the standard exception
mechanism, as there is already a lot of derived types (and many allow a
string parameter which will be incorporated in the what() return)
--
Just because nobody complains does not mean all parachutes are perfect.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> Apparently Google is your friend. After some minimal amount of effort, I
> came across a very well-written forum post which helpfully explains that
> in Debug mode all variables are guaranteed to be initialised to default
> values, whereas in Release mode variables take on whatever random
> gibberish happens to be in memory, unless you remember to explicitly
> initialise them to something sane.
Initializing variables takes clock cycles, which is why C hackers don't
want them being initialized in situations where they are going to be
assigned to anyway... (As if this matters at all in 99.999% of the cases.)
Many compilers will analyze the code and give a warning about variables
being used uninitialized, but this analysis will always be inevitably
limited (because, as you may know, proving that eg. a variable is used
uninitialized is an improvable problem.)
There are some external tools that can be used to analyze the program
while it runs, and will detect things like this (as well as memory leaks
and accessing freed memory or out-of-bound accesses.) The only free one
I know of is valgrind. However, it only works on Linux and Mac OS X. No
such luck in Windows.
There are commercial programs that do the same (and more.) One that I know
of is AQtime.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> This would be acceptable if VC offered some how to find out WHAT
> TEMPLATE it was attempting to expand when the error occurred. But no, it
> just shows you the source code for the STL (or Boost or whatever) and
> points at the line on which the problem was actually detected. There
> seems to be no way that I can discover what line of which file resulting
> in this template being invoked in the first place - and THAT is surely
> where the problem is, not in STL itself.
All compilers I know if will give you the full chain of calls that
ended up in the erroneous line. (And usually looking at the first error
message that refers to your code will immediately reveal the problem.)
I would be quite surprised if VC didn't do this.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 24/05/2013 06:00 PM, Warp wrote:
> All compilers I know if will give you the full chain of calls that
> ended up in the erroneous line. (And usually looking at the first error
> message that refers to your code will immediately reveal the problem.)
>
> I would be quite surprised if VC didn't do this.
...which probably just means I need to go discover where in the UI this
information is hidden. It's probably quite simple once you know where to
look.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> in Debug mode all variables are guaranteed to be initialised to default
>> values, whereas in Release mode variables take on whatever random
>> gibberish happens to be in memory, unless you remember to explicitly
>> initialise them to something sane.
>>
>> Ouch.>_<
>
> That's why options like -Wall -Wextra -pedantic -Wold-style-cast are my
> friends with g++.
>
> I do not know MSVC enough, but it might have that kind of warnings too
> (on explicit demand, of course)
I think MSVC actually *does* output warnings... It's just that every
time you compile the sources, it generates many hundred lines of
"stuff", and any warning messages are swamped by all the other output. I
think I've seen a warning or two flash past, but it would be quite
time-consuming to actually go read them all. (And most warnings are just
"printf is deprecated; please use printf_s instead".)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 24/05/2013 05:58 PM, Warp wrote:
> Initializing variables takes clock cycles, which is why C hackers don't
> want them being initialized in situations where they are going to be
> assigned to anyway... (As if this matters at all in 99.999% of the cases.)
I was thinking about this the other day. AFAIK, C was designed to run on
the PDP line of mainframes. Back in those days, the path to maximising
performance was to minimise the number of opcodes to be executed. That's
why we had CISC; the more work done per opcode, the fewer opcodes and
hence the fewer fetch / decode cycles wasted.
Today, it appears to me that the number of opcodes is nearly moot. If
you do 20 unnecessary arithmetic operations, on today's super-scalar
architectures with deep pipelining, it'll probably run most of that lot
in parallel anyway. But if your code causes a CACHE MISS or a BRANCH
MISPREDICTION... it will cost you HUNDREDS of compute cycles.
In summary, it seems that doing work twice is no longer expensive.
Accessing memory in the wrong order and doing indirect jumps are the
expensive things now. (So... I guess that makes dynamic dispatch really
expensive then?)
> Many compilers will analyze the code and give a warning about variables
> being used uninitialized, but this analysis will always be inevitably
> limited (because, as you may know, proving that eg. a variable is used
> uninitialized is an improvable problem.)
Yeah, I think VC might actually be giving me warnings, but they're
getting lost in the miles of other output.
Part of the problem is probably also that I don't completely understand
how variable initialisation works in C++. (E.g., class constructors get
called whether you want them to or not, so if it has a nullary
constructor, it should be initialised to something sane...)
> There are some external tools that can be used to analyze the program
> while it runs, and will detect things like this (as well as memory leaks
> and accessing freed memory or out-of-bound accesses.) The only free one
> I know of is valgrind. However, it only works on Linux and Mac OS X. No
> such luck in Windows.
Oh, really? I wasn't aware valgrind didn't work on Windows... (Then
again, it's not like I've looked into it. I doubt I could even figure
out how to work such a complex tool.)
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> I think MSVC actually *does* output warnings... It's just that every
> time you compile the sources, it generates many hundred lines of
> "stuff", and any warning messages are swamped by all the other output. I
> think I've seen a warning or two flash past, but it would be quite
> time-consuming to actually go read them all.
In principle you should get 0 warnings for a properly-written program.
> (And most warnings are just
> "printf is deprecated; please use printf_s instead".)
That particular warning can be turned off in VC. A google search should
tell you how.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> On 24/05/2013 05:58 PM, Warp wrote:
> > Initializing variables takes clock cycles, which is why C hackers don't
> > want them being initialized in situations where they are going to be
> > assigned to anyway... (As if this matters at all in 99.999% of the cases.)
> I was thinking about this the other day. AFAIK, C was designed to run on
> the PDP line of mainframes. Back in those days, the path to maximising
> performance was to minimise the number of opcodes to be executed. That's
> why we had CISC; the more work done per opcode, the fewer opcodes and
> hence the fewer fetch / decode cycles wasted.
C was also developed in a time where compilers did almost zero
optimization. Most C programs were "hand-optimized" for something
like 20 years, before compiler technology caught up, making such
manual optimization almost completely moot.
(Just as a concrete example, "i * 2" would for a quite long time produce
an actual multiplication opcode, which was extremely slow especially back
in those days, which is why it was usually written as "i << 1" by C hackers,
which produces a bit shift opcode that's much faster. Nowadays compilers
will detect both situations and use whatever is faster in the target
architecture, making the whole manual optimization completely moot.)
> In summary, it seems that doing work twice is no longer expensive.
> Accessing memory in the wrong order and doing indirect jumps are the
> expensive things now. (So... I guess that makes dynamic dispatch really
> expensive then?)
Calling a virtual function in C++ is no slower in practice than calling
a regular function. That additional indirection level is a minuscule
overhead compared to everything else that's happening with a function call.
It might make some difference in rare cases with very small functions
that are called in a really tight inner loop that runs for millions of
iterations, especially if said function can be inlined by the compiler.
However, it's rare to need dynamic dispatch in such situations anyway.
> Part of the problem is probably also that I don't completely understand
> how variable initialisation works in C++. (E.g., class constructors get
> called whether you want them to or not, so if it has a nullary
> constructor, it should be initialised to something sane...)
Basic types do not get implicitly initialized (except in some
circumstances), user-defined types do. In other words, if you have
an int and a std::string as a member of a class, the int won't be
implicitly initialized and you have to explicitly initialize it in
the constructor. The std::string will, because it's a class, and thus
doesn't need to be explicitly initialized.
A raw pointer is a basic type and thus will likewise not be implicitly
initialized. std::shared_ptr is a class and will always be initialized
(to null.)
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
>> I was thinking about this the other day. AFAIK, C was designed to run on
>> the PDP line of mainframes. Back in those days, the path to maximising
>> performance was to minimise the number of opcodes to be executed. That's
>> why we had CISC; the more work done per opcode, the fewer opcodes and
>> hence the fewer fetch / decode cycles wasted.
>
> C was also developed in a time where compilers did almost zero
> optimization. Most C programs were "hand-optimized" for something
> like 20 years, before compiler technology caught up, making such
> manual optimization almost completely moot.
From what I can tell, C was developed at a time when you actually ran
CPP by feeding in your source files and header files on several tapes,
and having CPP output the final, combined output onto another tape. You
then unload CPP, load CC, and then it reads the tape in and spews out
the machine code as it reads. (Which is why you need forward
declarations and stuff; the source code is literally too large to hold
in memory all at once.)
When 16K was a huge amount of RAM, these kinds of gyrations were
necessary. On my dev box, with 4GB of RAM, it seems kinda silly...
(Having said that, if you have a microcontroller with 2K of RAM and 4K
of ROM, then C is about the only language that can target it.)
> (Just as a concrete example, "i * 2" would for a quite long time produce
> an actual multiplication opcode, which was extremely slow especially back
> in those days, which is why it was usually written as "i<< 1" by C hackers,
> which produces a bit shift opcode that's much faster. Nowadays compilers
> will detect both situations and use whatever is faster in the target
> architecture, making the whole manual optimization completely moot.)
Curiously, the Haskell compiler does heaps and heaps of really
high-level optimisations like removing redundant computations, inlining
functions, transforming nested conditional tests and so on. But it
utterly fails to perform trivial low-level optimisations like replacing
arithmetic with bitshifts. Partly because that stuff obviously varies
somewhat per-platform - and partly because it's not very "exciting".
Design a radical new optimisation pass and you can publish a paper on
it. Implement mundane stuff that other compilers have done for years and
nobody will care.
(This is in part why there's now an LLVM backend. Hopefully LLVM will do
this kind of stuff for you...)
>> In summary, it seems that doing work twice is no longer expensive.
>> Accessing memory in the wrong order and doing indirect jumps are the
>> expensive things now. (So... I guess that makes dynamic dispatch really
>> expensive then?)
>
> Calling a virtual function in C++ is no slower in practice than calling
> a regular function. That additional indirection level is a minuscule
> overhead compared to everything else that's happening with a function call.
It's not so much the jump, it's the not being able to start prefetching
the instructions at the other end until after the target address has
been computed, leading to a pipeline bubble.
That said, if you're running JIT-compiled code with garbage collection
and whatnot, the overhead of a few extra jumps is probably moot. (E.g.,
if your code is Java or C# or Python or something.)
>> Part of the problem is probably also that I don't completely understand
>> how variable initialisation works in C++.
>
> Basic types do not get implicitly initialized (except in some
> circumstances), user-defined types do.
Yeah, for some reason I had it in my head that it's whether the variable
is a class member or just a local variable. What you said makes more sense.
> A raw pointer is a basic type and thus will likewise not be implicitly
> initialized.
So it points to random memory?
> std::shared_ptr is a class and will always be initialized
That is what I thought.
> (to null.)
That's the bit I failed to anticipate.
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Le 2013-05-24 17:08, Orchid Win7 v1 a écrit :
>> A raw pointer is a basic type and thus will likewise not be implicitly
>> initialized.
>
> So it points to random memory?
>
Yes. C++ still allows you to shout yourself in the foot.
--
/*Francois Labreque*/#local a=x+y;#local b=x+a;#local c=a+b;#macro P(F//
/* flabreque */L)polygon{5,F,F+z,L+z,L,F pigment{rgb 9}}#end union
/* @ */{P(0,a)P(a,b)P(b,c)P(2*a,2*b)P(2*b,b+c)P(b+c,<2,3>)
/* gmail.com */}camera{orthographic location<6,1.25,-6>look_at a }
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 30/05/2013 10:46 PM, Francois Labreque wrote:
> Le 2013-05-24 17:08, Orchid Win7 v1 a écrit :
>>> A raw pointer is a basic type and thus will likewise not be implicitly
>>> initialized.
>>
>> So it points to random memory?
>
> Yes. C++ still allows you to shout yourself in the foot.
Oh, I wasn't disputing that. Just checking.
Today I discovered that some of the code I copy-pasted actually had some
memory allocation in it, and I hadn't explicitly deallocated it again.
To be clear... I only need to do explicit deallocation if I've done
explicit allocation in the first place, right?
unsigned char foo[512];
vs
unsigned char * foo = new[512];
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> To be clear... I only need to do explicit deallocation if I've done
> explicit allocation in the first place, right?
Every 'new' must have a correspondent 'delete'. If you don't write 'new'
then you don't have to worry about any deletes either.
Of course the exception to this is if you are using a smart pointer like
std::shared_ptr or std::unique_ptr, in which case you do write 'new',
but let the smart pointer do the 'delete' for you.
If you really need to explicitly allocate memory, then it's usually a
good idea to use such a smart pointer, because they will make sure that
they will delete the object when the last smart pointer to it dies, and
delete it only once.
The thing is, even if you have written one 'new' and one 'delete' in your
code, the object might be being deleted more than once. This is because of
the wonderful thing in C++ that is copying and assigning of classes.
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 31/05/2013 09:41 PM, Warp wrote:
> Orchid Win7 v1<voi### [at] dev null> wrote:
>> To be clear... I only need to do explicit deallocation if I've done
>> explicit allocation in the first place, right?
>
> Every 'new' must have a correspondent 'delete'. If you don't write 'new'
> then you don't have to worry about any deletes either.
>
> Of course the exception to this is if you are using a smart pointer like
> std::shared_ptr or std::unique_ptr, in which case you do write 'new',
> but let the smart pointer do the 'delete' for you.
>
> If you really need to explicitly allocate memory, then it's usually a
> good idea to use such a smart pointer, because they will make sure that
> they will delete the object when the last smart pointer to it dies, and
> delete it only once.
>
> The thing is, even if you have written one 'new' and one 'delete' in your
> code, the object might be being deleted more than once. This is because of
> the wonderful thing in C++ that is copying and assigning of classes.
Without revealing too many details about the product I'm working on, it
deals with byte-level processing of binary protocol data. So there's A
LOT of char* variables floating around the place. In short, it's just
the sort of code where a tiny bug will make the program output gibberish
or crash spectacularly. It makes me feel twitchy inside...
The other fun thing is that sometimes one function calls another
function, and the other function returns a char*. So "you" didn't
allocate anything, but the function you called did, and you need to
remember to deallocate it. (Arguably that's poor design, but hey, I
didn't write the code...)
PS. What black magic is it that makes delete[] work correctly?
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
Orchid Win7 v1 <voi### [at] dev null> wrote:
> Without revealing too many details about the product I'm working on, it
> deals with byte-level processing of binary protocol data. So there's A
> LOT of char* variables floating around the place. In short, it's just
> the sort of code where a tiny bug will make the program output gibberish
> or crash spectacularly. It makes me feel twitchy inside...
If a program needs to use lots of raw pointers to dynamically allocated
memory, it requires quite a lot of experience and following certain design
principles in order for the code to be safe. (There are situations where
smart pointers just can't be used. For example a smart pointer won't help
you a bit if you need a pointer that points to some element of a
dynamically allocated array.)
I freely admit this is just an evil that one has to live with if one is
programming with a language of the C family. However, having to actually
write that kind of code is a lot less frequent than one might think,
especially if you are writing the entire program and you get to design it
properly from the very start.
In most cases one should avoid allocating arrays directly with 'new',
and use std::vector instead. Then, if possible, one should avoid having
raw pointers pointing to the elements of the vector, except in very simple
situations (where it's trivial to see that no such pointer will get
invalidated or be used after the vector has been destroyed.) Prefer
indexing the vector object directly, if possible. (Or use vector iterators.
Many compilers can add checks to them in debug mode, which can help quite
a lot.)
Sure, there are situations where std::vector won't cut it, or where such
pointers just have to be used, but these situations are not all that
common in practice.
> The other fun thing is that sometimes one function calls another
> function, and the other function returns a char*. So "you" didn't
> allocate anything, but the function you called did, and you need to
> remember to deallocate it. (Arguably that's poor design, but hey, I
> didn't write the code...)
That's extremely poor design, and is one of the big no-no's in C++
programming. It's asking for trouble.
> PS. What black magic is it that makes delete[] work correctly?
It depends on the compiler and the runtime library, but most probably
there's metadata at the beginning of an allocated block of memory that
says how many elements there are in said block. 'delete[]' probably just
blindly takes that value (which is probably located at the pointer's
position minus some fixed offset) and assumes there are that many elements
in the array. (Obviously it will break horribly if you try to delete[]
a pointer that's not pointing to the first element of a dynamically
allocated array.)
--
- Warp
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |
|  |
|
 |
On 5/24/2013 12:00 PM, Warp wrote:
> Orchid Win7 v1 <voi### [at] dev null> wrote:
>> This would be acceptable if VC offered some how to find out WHAT
>> TEMPLATE it was attempting to expand when the error occurred. But no, it
>> just shows you the source code for the STL (or Boost or whatever) and
>> points at the line on which the problem was actually detected. There
>> seems to be no way that I can discover what line of which file resulting
>> in this template being invoked in the first place - and THAT is surely
>> where the problem is, not in STL itself.
>
> All compilers I know if will give you the full chain of calls that
> ended up in the erroneous line. (And usually looking at the first error
> message that refers to your code will immediately reveal the problem.)
>
> I would be quite surprised if VC didn't do this.
The version of VS C++ I use at work does not give a reference chain for
any error. In a number of cases I am unable to discern what caused the
cited file to be invoked.
Regards,
John
Post a reply to this message
|
 |
|  |
|  |
|
 |
|
 |
|  |