Is it possible to initialize reference variables later? - c++

Best explained with an example:
Class banana {
int &yumminess;
banana::banana() {
//load up a memory mapped file, create a view
//the yumminess value is the first thing in the view so
yumminess = *((int*)view);
}
}
But that doesn't work :/ there is no way I can know where the view is going to be when I dreclare the "yumminess" reference variable. Right now i just use a pointer and dereference it all the time, is there any way to bring this little extra bit of convenience to my class?

In short: No, it's intentionally not possible.
Think twice: Something like uninitialized references cannot really exist; such wouldn't make sense at all.
Thus they'll need to be set at the time of construction of the enclosing class, or at a point of static initialization.
You'll need to use pointers for such case.
Besides note that
yumminess = (int*)view;
would be wrongly casted (to a pointer) anyway.
"Right now i just use a pointer and dereference it all the time ..."
That's also easy to overcome writing an appropriate member function to access the reference.
int* yumminess;
// ...
int& yumminessRef() {
if(!yumminess) {
throw some_appropriate_exception("`yumminess` not initialized properly.");
}
return *yumminess;
}

No, not directly.
If you think the pointer is inconvenient, have a look at std::optional.

Related

Is use count on `const std::shared_ptr<...>' mutable?

I'm trying to adapt some pre-existing code to make use of std::shared_ptr<...>. It is a `message passing system' so the basic context is:
Public Method:
void writeReport(std::shared_ptr<const ReportBase> pReport) {
/* This is a public method for writing a report. I might do
additional stuff in here but end by forwarding to the
private method. */
writeReport_(pReport);
}
Private Method:
void writeReport_(std::shared_ptr<const ReportBase> pReport) {
if( certain conditions )
processReport_(pReport);
writeBytes_(serialize(pReport));
}
Processing Method:
void processReport_(std::shared_ptr<const ReportBase> pReport) {
processReportImpl(pReport);
if( certain other conditions )
reportDeque_.push_back(pReport);
}
Of the above pseudo-code, for example, processReport_(...) might be the only method which, under certain conditions, would want to actually store the record. The other methods are simply interested in the contents of the object pointed to. So, were it not for the need to sometimes copy the shared_ptr in processReport_(...) (i.e., 'store' the record), I would simply pass const ReportBase * to all my nested functions and avoid the overhead of pass-by-value (i.e., use count increments).
So, I want to pass std::shared_ptr<const ReportBase>& (and maybe && where appropriate) but want to preclude some rogue nested method from actually modifying what the pointer points to. So I think I want to pass const std::shared_ptr<const ReportBase>& to prevent that...
... but, again, in processReport_(...) I'll sometimes want to make a copy to store the record.
Which finally leads me to the question(s)...
is use count on a std::shared_ptr mutable?
Why can (or can't) I do a copy assignment on a const std::shared_ptr<...> to a std::shared_ptr<...>?
Does the const make the entire control block of the shared_ptr const? Or does the leading const only apply to the raw pointer value?
And if someone wants to answer tangentially 'don't worry so much about passing by value into nested functions' or 'I have a completely different approach for you' then I'd be interested to hear that too.
std::shared_ptr stores a pointer to the control block, which is allocated on the heap. After all, it has to be shared across all copies of that shared_ptr. So, when you apply a const to your std::shared_ptr, you are merely making that pointer const. The control block object being pointed to remains non-const. Think ControlBlock* const. Therefore, there is no need for an explicit mutable keyword there, although logically, the control block is indeed mutable.
If I understand your question correctly I would use a function like this
void processReport(const std::shared_ptr<ReportBase> &report) {
if( certain other condition ) {
reportDeque_.push_back(report); // will make the copy here
}
With the const std::shared_ptr<ReportBase> & you don't increment the use count, so if you add it to the vector it will have to be a copy of the shared_prt and therefore increase the count, if not the count stays the same.

C++: can a field object know its "parent" without storing a pointer?

Suppose I have this setup:
struct XView;
struct X
{
...
XView view;
};
Type XView is only used for this one field; it is internal too, so instantiating it from outside, i.e. using it for anything else is prohibited.
So, assuming any object of XView type is an X::view field, is it possible to find address of X from address of XView, staying fully within behavior defined by C++ standard and without type-punning? I.e. is it possible to do something like this:
void XView::some_function ()
{
X& this_x = some_computations_involving (this);
}
I can of course store a pointer, so this would become as trivial as x = *this->parent_x, but would like to do without one if possible.
EDIT: Note that I need an answer without type-punning involved, otherwise I'd rather use that "just store a pointer" solution.
First approach is to make XView the first member of X, then you can do this:
void XView::some_function ()
{
X & this_x = reinterpret_cast<X&>(*this);
}
Second approach is to use offset when XView is not the first member of the X.
Techinically speaking both of these approaches are same if there is no virtuality involved, only that the first approach is a special case (i.e when offset = 0) of the second approach which is the general case.
As for the edit, I think, without casting it is not possible. You have to store the pointer in XView, Or maintaining a map (or some other data structures) of pointers.
The most important thing is whether you really need accessing the parent object from child object and not vice-versa.
I would suggest you using some kind of bi-directional linked list or something like this.
Could your code be refactored to be more object-oriented? (and possibly using the inheritance (and calling the parent by using the super::some_function...)

Best way to return an object in c++?

I'm pretty noobish when it comes to c++, what is the better way of returning an object? I'm coming from the scripting world where Objects are always references, and am trying to achieve the same notion ... I'm basing this off of When to pass by reference and when to pass by pointer in C++?, where one user stated: "A good rule of thumb: "Use references when you can and pointers when you have to"."
// basic layer class
class Layer { private: Channel channel; // NEVER NULL };
// return object by pointer
Channel *Layer::getChannel() {
return &channel;
};
// return by reference
Channel& Layer::getChannel() {
return channel;
};
The problem with the second version is that the compiler will accept this line:
Channel channel = layer.getChannel(); // creates a copy BAD
when it should be:
Channel &channel = layer.getChannel(); // reference good
Is there any way to enforce a caller of the second option to force it to not create a new channel, or is the first option better anyways, even if it will never be NULL?
You need to adjust the Channel class itself so that it isn't copyable. If it is copyable, the user can copy it, and nothing you do can prevent it.
If copying is not a meaningful operation, then you can "disable" it. Simply define the copy constructor (Channel(const Channel&)) and the assignment operator (Channel& operator=(const Channel&)) to be private. Then any attempt at copying the class will result in a compile error.
On a side note, as others have mentioned, C++ is not the scripting languages you're familiar with. Everything is not a reference, and you're only setting yourself up for a world of pain by pretending otherwise. In C++, it is common to allocate objects on the stack, and pass objects by value, rather than passing references and pointers around.
Returning a reference (or const reference) is the normal way for a getter method to give the caller direct access to a member variable, so I'd recommend the second version of getChannel().
If you want to prevent callers from making inappropriate copies of Channel, you can accomplish that by making its copy constructor private. (If you want to prevent everything from making copies, even Channel itself, you can declare the constructor private and then not implement it.) But you should only do this if making a copy would actually be nonsensical, e.g. if the class represents some sort of underlying resource that can't be copied. Don't forbid copying just because you think the caller shouldn't need to; that's the caller's decision to make.
Return a copy of the object itself when copying isn't expensive for your purposes, and when you don't need to be able to change the original. This should be the default.
Channel Layer::getChannel() { return channel; };
Return by reference or pointer when copying is expensive or when you might want to change the value. Returning by reference allows you do to things like this:
layer.getChannel().clear();
And have it act on the channel that's in that layer.
Returning a pointer is similar to returning a reference except that it gives you a little more flexibility, in that the pointer can pointer to no object at all. I often a pointer when I want to be able to use store the "channel" in another class. I'd then do
class MyClass
{
// ...
void setChannel(Channel *pC) { m_pChannel = pC; }
private:
Channel * m_pChannel; // pointer to a channel that came from layer
}
Since you're returning a reference to the object, you are giving the users of the class direct access to the object, and if you're going to do that, why are you making the object private? Just make it public.
You can't stop a caller to create a new instance even when you use the pointer-return-version.
Channel* channel = new Channel(*layer.getChannel());
I know there is a way to achieve this goal. (For example, making Channle's ctor private so only it's static member function or its friend functions can create it.) However, I don't think this is the point of your question.
The point is that when you are making the member function returning either reference or pointer, you give a caller options he can choose whether he wants to copy it or reference it. Also, you can make your intention more clear by adding const to make it read-only.
For your case, I'd go for reference-return-version as the Channel cannot be null. If you do not want them to change the member variable, return const reference. Remember there is no single best way to decide return value type as it depends on what you want to say. Hope it helps! :)
Most important is maintaining readability with the code that's around you. "When in Rome, do as the Romans do." is important. You write it once, but everyone who has to maintain your code has to read it. If all of a sudden your code follows different guidelines than everyone around you, that means they need to first figure out your style, then figure out what you're doing...
One approach I've seen work very well is having pointers for things you change and const references for things you don't:
class Passenger {
...
};
class Car {
public:
int speed() const { return speed_; }
void set_speed(int speed) { speed_ = speed; }
const Passenger& passenger() const { return pass_;}
Passenger* mutable_passenger() { return &pass_; }
private:
int speed_;
Passenger pass_;
};
Clients of this class can do:
const Passenger& pass = car.passenger(); // no copy, but don't need to deal with NULL ptrs.
Other answers suggesting making copying a compile error are good ones.

Getter and setter, pointers or references, and good syntax to use in c++?

I would like to know a good syntax for C++ getters and setters.
private:
YourClass *pMember;
the setter is easy I guess:
void Member(YourClass *value){
this->pMember = value; // forget about deleting etc
}
and the getter?
should I use references or const pointers?
example:
YourClass &Member(){
return *this->pMember;
}
or
YourClass *Member() const{
return this->member;
}
whats the difference between them?
Thanks,
Joe
EDIT:
sorry, I will edit my question... I know about references and pointers, I was asking about references and const pointers, as getters, what would be the difference between them in my code, like in hte future, what shoud I expect to lose if I go a way or another...
so I guess I will use const pointers instead of references
const pointers can't be delete or setted, right?
As a general law:
If NULL is a valid parameter or return value, use pointers.
If NULL is NOT a valid parameter or return value, use references.
So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.
If it's valid to call the getter of a object containing a NULL pointer, it should return a pointer. If such a case is an illegal invariant, the return value should be a reference. The getter then should throw a exception, if the member variable is NULL.
Your code looks a great deal as if you're accustomed to a different language -- in C++ using this->x (for one example) is relatively unusual. When the code is at all well written, so is using an accessor or mutator.
Though I'm fairly unusual in this particular respect, I'll go on record (yet again) as saying that forcing client code to use an accessor or mutator directly is a bad idea. If you honestly have a situation where it makes sense for client code to manipulate a value in your object, then the client code should use normal assignment to read and/or write that value.
When/if you need to control what value is assigned, operator overloading lets you take that control without forcing ugly get/set syntax on the client code. Specifically, what you want is a proxy class (or class template). Just for one example, one of the most common situations where people want get/set functions is something like a number that's supposed to be restricted to some particular range. The setXXX checks the new value for being in range, and the getXXX returns the value.
If you want that, a (fairly) simple template can do the job much more cleanly:
template <class T, class less=std::less<T> >
class bounded {
const T lower_, upper_;
T val_;
bool check(T const &value) {
return less()(value, lower_) || less()(upper_, value);
}
void assign(T const &value) {
if (check(value))
throw std::domain_error("Out of Range");
val_ = value;
}
public:
bounded(T const &lower, T const &upper)
: lower_(lower), upper_(upper) {}
bounded(bounded const &init)
: lower_(init.lower), upper_(init.upper)
{
assign(init);
}
bounded &operator=(T const &v) { assign(v); return *this; }
operator T() const { return val_; }
friend std::istream &operator>>(std::istream &is, bounded &b) {
T temp;
is >> temp;
if (b.check(temp))
is.setstate(std::ios::failbit);
else
b.val_ = temp;
return is;
}
};
This also makes the code much closer to self documenting -- for example, when you declare an object like: bounded<int>(1, 1024);, it's immediately apparent that the intent is an integer in the range of 1 to 1024. The only part somebody might find open to question is whether 1 and/or 1024 is included in the range. This is considerably different from defining an int in the class, and expecting everybody who ever looks at the class to realize that they're supposed to use the setXXX to enforce some (at that point unknown) set of bounds on the values that can be assigned.
When you embed one of these in a class, you make it a public variable, and the range is still enforced. In the client code, there's no real argument over syntax -- you're just assigning to a public variable, like you would any other -- with the minor detail that attempting to assign a value that's out of range will throw an exception. In theory, the class should probably take a policy template-parameter to specify exactly what it does in that case, but I've never had a real reason to bother with that.
The best thing is to provide a real OO interface to the client that hides implementaton details. Getters and Setters are not OO.
As others have said, use pointers if null is a possibility.
In most cases, I prefer to use references when possible. Personally, in my code, I like to use the distinction between pointers and references to signal ownership. I think of calls with references as "loaning" an object to another function or class. The original class that passed or returned the reference still owns it, and is responsible for its creation, maintenance and clean up. When my code passes a non-const pointer, on the other hand, it usually means that there's some kind of transfer or sharing of ownership going on, with all the responsibilities that entails.
(And yes, I usually use smart pointers. Those are akin to references in my mind. I'm talking about lower level code than that here.)
whats the difference between them?
The reference is an alias of the thing(it is the thing*). A pointer is the address of the thing. If there's a chance that what's pointed to won't be there, then you probably don't want to return references. References tell the caller "I'm going to give you an alias that will exist when I return it to you". In fact there's really no way to check the reference to see if what's underlying is valid.
With the pointer, semantically, you are implying that the caller may wish to check to see if Member exists before using it. Ussually this is done with a NULL check.
Ultimately there's no "right" answer. It depends on the class's contract and if the caller will/should/wants to check whether "Member" is still around.
The short answer is pointers for things that can be pointed elsewhere and references for "unseated" aliases.
In addition to the other answers, if you choose references for the getter don't write it like in your example:
YourClass &Member(){
return *this->pMember;
}
Your getter actually allows setting, as in instance->Member() = YourClass(); and thus bypassing your setter. This might not be allowed if YourClass is noncopyable, but is still another thing to have in mind. Another drawback is the getter is not const.
Instead, write your getter like this:
const YourClass &Member() const {
return *this->pMember;
}
+1 on questioning the use of setters and getters. If you must use them and have the possibility of nulls consider using boost::shared_ptr. This way ownership is handled for you.
Jonathan, what compiler are you using? There's a great chance that shared_ptr already comes shipped with it as part of the compiler's TR1 implementation.

Difference between references and pointers [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
What does Class& mean in c++ and how is it different from Class*?
Class& foo;
Class* foo;
The & version represents a reference while the * version represents a pointer. The difference is far too big for a typical SO post. I suggest you start at the C++ FAQ lite
http://www.parashift.com/c++-faq-lite/references.html
I usually don't like to answer posts with a "you should use google" answer. However this is one topic that I highly advise you google. In particular google "c++ pointers vs. references". There is a wealth of information available on this topic and the discussions on those pages will trump anything we'll write here.
The * is a pointer, the & is a reference. The difference between the two is that a pointer is an area of memory that must be dereferenced, eg. by means of the -> operator in order to be "seen" as a class instance. A reference is instead an "alias", just an alternative name for the same class instance. You don't need to use the -> operator with a reference. You use the dot operator.
Personally, I rarely used the references, mostly when I had a value object that I allocated on the stack. The new operator always returns a pointer, which you then have to dereference. Moreover, one of the most problematic issues of the references is that you cannot set them to NULL. In some cases, it is handy to have a function that accepts either an object pointer or NULL. If your function accepts a reference, you cannot pass a NULL (you could use the Null object pattern, however)
A Class * can point at any class object, or none.
A Class & always points to exactly one class object, and can never point to a different one.
Furthermore, I believe Bjarne is a member of the set of people who have asserted "arrays in C are broken beyond repair," a Class * can point at a whole ding-dang array of class objects, lined up one after the other in memory, and there is absolutely no way in C to tell whether a Class * points at one or many.
Another difference is that reference variables must be initialized. You cannot create a reference variable like what is shown in the sample code. That would produce a compiler error.
As stated you should google it, but to avoid misunderstanding:
References are NOT variables
References are NOT similar to pointers (but you can use them in a similar way)
Think of a Reference as a shortcut for the term that is assigned to it.
One additional tip that I would offer is the following:
Use references when you can, pointers when you have to. If the object is guaranteed to exist, you should probably use a reference. If it is not, then you probably have to use a pointer.
One additional advantage is that references remove ambiguity on ownership. As soon as a maintenance programmer sees a pointer, they'll start to wonder if they should delete it.
Check this example out:
// Wrapper class using a reference because the wrapped object always exists
class Wrapper
{
public:
// If the wrapped is guaranteed to exist at creation, do it this way
Wrapper(Wrapped& wrapped):_wrapped(wrapped) { /* empty */ }
// put extra methods here.
int getWrappedValue() const { return _wrapped.getValue(); }
private:
Wrapped& _wrapped; // This object always exists and is valid
};
// Wrapper class written to support a possibly non-existent wrapped object.
class Wrapper
{
public:
Wrapper(Wrapped* wrapped = 0):_wrapped(wrapped) { /* empty */
void setWrappee(WRappee* wrapped) { _wrapped = wrapped; }
int getWrappedValue() const; // Not making inline -- more complex
private:
Wrapped* _wrapped; // Always check pointer before use
};
int Wrapper::getWrappedValue() const
{
if (_wrapped)
{
return _wrapped->getValue();
}
else
{
return -1; // NOTE, this is a contrived example -- not getting into exceptions
}
}
A reference (&) is just the same as a pointer (*), except that the C++ compiler ensures it not to be NULL. However, it can still be a dangling pointer (a pointer variable that has no reference such that it is garbage and invalid for any use).