Understanding how read the `const`ness of c++ code - c++11

In my attempt to teach myself C++, I was hoping to get some help in how to read the const-ness of a expression/function etc. For example, the code below:
const screen &display(std::ostream &output) const {
do_display(output); return *this;
}
In the above code. there are two const declarations in the function display. In "English" how is that properly read? example: the first const is a const to reference or const to type screen? etc. and what exactly does the const-ness mean/imply when a reference is const etc. I have tried reading up on it but is still a bit muddy at this point.
Feel free to point to a youtube video or other reference material. Hopefully the material that is very clear.

I've always found that the simplest way to remember it is:
const applies to whatever is to the left of it, unless there isn't anything to the left of it, in which case it applies to whatever is to the right of it.
So, you have a const method that returns a const reference to a screen.
A const reference means you can't modify the referenced object. The const method means that the method won't modify the object it's being called on (the this pointer inside that method will be to a const object).

You read it right to left.
You have a constant method that returns a reference to a screen that is constant.
Returning a constant reference means you cannot modify what is returned.
If you call the method and assign it to some variable, the variable must use the const keyword. The only exception to this is if you cast the returned reference from the method to something that is not constant.
Here's a helpful link for more detail on the right to left rule:
http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html
That's actually written by a professor at UCSD (and he's pretty good).
The const on the right side of the method just means you can't modify any instance variables inside the function (for the most part). There's a bit more to it, but for more detail, refer to:
Meaning of "const" last in a C++ method declaration?

Read it right to left.
int const & foo() const
const method which returns a...
int const & foo() const
Reference to a...
int const & foo() const
const int.
The const can go on either side of int. You can read it as a "constant integer" or a "integer which is constant".

In English it means:
display() is a constant method of its class (this is the 2nd const keyword) that takes a reference to a std::ostream class instance as its parameter, and returns a reference to a constant (this is the 1st const keyword) instance of the screen class.
A const reference means that this reference cannot be used to modify the object being referenced. You can use the reference only to access, but not change, the members of the class, or to invoke the class's const methods (like display() is a const method of its own class).

Related

Capture a local pointer by value and the rest by reference in a lambda

I would like to capture a local pointer in my lambda expression. Currently my code looks like this
MYButton* button;
button->onPress = [index,&](control*){
button->foobar(x, y);
};
I get the error
Error:(835, 13) variable 'button' cannot be implicitly captured
in a lambda with no capture-default specified
I was under the impression that using & in the capture clause meant capture everything in local scope by reference. In that case why am I getting this error ?
There is no capture default identified, because the capture default must be the first item in the captures. See cpp reference for details.
The correct code should be
MYButton* button;
button->onPress = [&,index](control*){
button->foobar(x, y);
};
Also, the capture index does not appear to be used. You can eliminate that, in which case the code would be
MYButton* button;
button->onPress = [&](control*){
button->foobar(x, y);
};
And, as Chris Dodd mentioned, the use of this lambda will probably be out of the scope of this code fragment, in which case you should capture by value to avoid a dangling reference:
MYButton* button;
button->onPress = [=](control*){
button->foobar(x, y);
};
From the cpp reference:
If a non-reference entity is captured by reference, implicitly or explicitly, and the function call operator of the closure object is invoked after the entity's lifetime has ended, undefined behavior occurs. The C++ closures do not extend the lifetimes of the captured references.
One more comment. While default capture looks nice on paper (one character, no fuss), I like to be explicit with captures to reduce the risk of errors like the ones pointed out above. It also makes it easier to identify which variables the lambda relies upon. In which case the code becomes:
MYButton* button;
button->onPress = [button](control*){
button->foobar(x, y);
};
This is just a change in style--it means the same as the example immediately prior to it, but should be less error-prone when revising code later on.

Problems using a std::map containing a class without copy operator (Gdiplus::Image)

It seems I am trying to fill a std::map with objects that are not copyable, and I have not achieved to do it yet.
General problem
I want to use std::map in order to store some objects of a type called Image (More precisely, it is Gdiplus::Image). I cannot write things like:
map<string, Gdiplus::Image> loadedImages ;
Gdiplus::Image newImage( CString("totoro.png") );
loadedImages.insert(std::pair<string, Gdiplus::Image>( "totoro", newImage ) );
Function "insert" seems to be the problem here. The compiler says:
'Gdiplus::Image::Image' : cannot access private member declared in class 'Gdiplus::Image'
I am not sure that it is the right explaination, but it seems that "Image" lacks of a public method used in function "insert". (Copy operator ? Copy constructor ?).
What I have tried
I tried to use references in the map, but it seems putting references in containers never works. I tried to use raw pointers, but I had got errors when I tried to delete all the images in the destructor. I happened across this other (and quite similar) question and I have begun to care about smart pointers. So now, I am trying, as recommended in the answer, with std::shared_ptr. However, my case is slightly different.
I want to write a function "find" that returns an image. "find" gives the image found in the map if the key (its path) exists, else it loads the image, add it to the map and returns it. So I cannot create a new image inside the parenthesis as I need the pointer.
The only version I came up with, that can compile is:
(Drawer.h)
#include <map>
#include <memory>
#include <Gdiplus.h>
using std::map ;
using std::shared_ptr ;
class CDrawer
{
public:
CDrawer(void);
~CDrawer(void);
void drawImage(string p_pathToPicture)
private:
map<string, shared_ptr<Gdiplus::Image>> m_loadedImages ; // Keep every image in memory instead of loading them each time. Each image has its path as a key.
Gdiplus::Image* findImage(string& p_path); // get the image from the map if the image is already loaded, else load it.
};
(Drawer.cpp) (Constructors and destructors are empty)
void CDrawer::drawImage(string p_pathToImage)
{
// get the bounding rectangle of the image
//...
Gdiplus::Image* l_image = findImage(p_pathToImage);
// Draw the image.
//...
}
Gdiplus::Image* CDrawer::findImage(string& p_pathToImage)
{
auto iterator = m_loadedImages.find(p_pathToImage);
if (iterator == m_loadedImages.end() ) // image not found, so we have not already loaded it
{
shared_ptr<Gdiplus::Image> l_newImage( new Gdiplus::Image( CString( p_pathToImage.c_str()) ) ); // Load the image (I know I have to add error code)
m_loadedImages.insert( std::pair<string, shared_ptr<Gdiplus::Image>>( p_pathToImage, l_newImage ) ); // Add the image to the list
return l_newImage.get() ;
}
else return iterator->second.get() ; // image found, so it is already loaded and we provide the existing one.
}
But it gives the following error during run time, when the destructor of Drawer is called:
Unhandled exception at 0x00C18CEE in MyProgramm.exe: 0xC0000005: Access violation reading location 0x02F36D78
Does someone knows where I am wrong, or if there is a simpler or better solution?

assigning value to shared_ptr <IplImage>

i am using obj C and i am having problem with assigning const IplImage* to the shared_ptr
i have defined a type as below
typedef std::shared_ptr<const IplImage> SharedImage;
and then i create an instance of it assign the instance to const IplImage* image.
how do i do that?
i understand that i have to initialize the IplImage that my shared_ptr is pointing to. so i have tried something like this, no error but unsure how to assign the variable image to it.
SharedImage shared_image(new const IplImage(*cvCreateImage(size, IPL_DEPTH_32F, 1)));
i tried shared_image.get() = image;
but it gives me error. any suggestion please? thank you in advance!
You should be able to use reset
shared_image.reset(image);
This interface would also allow you to set the corresponding deleter (if not the default). This capability would not exist with any of the approaches you were looking for

Passing NSTextField Pointer to IOUSBInterfaceInterface182 Callback

I'm doing an asynchronous read from a USB printer. The read works correctly. My trouble is updating a NSTextField from within the callback.
-(IBAction)printTest:(id)sender
{
// Setup... then:
NSLog(#"starting async read: %#", _printerOutput);
NSLog(#"_printerOutput pointer = %p", _printerOutput);
result = (*interface)->ReadPipeAsyncTO(interface,
1,
readBuffer,
numBytesRead,
500,
1000,
USBDeviceReadCompletionCallback,
&(_printerOutput)
);
The callback is defined as:
void USBDeviceReadCompletionCallback(void *refCon, IOReturn result, void *messageArg)
{
NSTextField *printerOutput = (__bridge NSTextField *) messageArg;
NSLog(#"_printerOutput pointer = %p", printerOutput);
}
The pointer loses its value when inside of the callback.
starting async read: <NSTextField: 0x10221dc60>
_printerOutput pointer = 0x10221dc60
_printerOutput pointer = 0x0
I've looked in many places trying to mimic different ways to pass in the pointer. There can be only one correct way. :)
Another variation on the theme: (__bridge void *)(_printerOutput). This doesn't work, either.
I understand that the callback is of type IOAsyncCallback1.
Other URLs of note:
http://www.google.com/search?client=safari&rls=en&q=another+usb+notification+example&ie=UTF-8&oe=UTF-8 and updating UI from a C function in a thread
I presume _printerOutput is an NSTextField*?
First, is there a particular reason why are you passing an NSTextField** into the callback? (Note the ampersand in the last argument you're passing to ReadPipeAsyncTO.)
Second, I'd avoid ARC with sensitive code, just as a precaution.
Third, from what I see, last argument of ReadPipeAsyncTO is called refcon. Is it a coincidence that callback's first argument is called refCon? Note you're trying to get a text field from messageArg, not refCon.
To extend on my third point…
ReadPipeAsyncTO has an argument called refcon. This is the last argument.
Please pass _printerOutput there. Not a pointer to _printerOutput (do not pass &(_printerOutput)) -- _printerOutput is already a pointer.
Now finally. Look at the first argument of the callback. It's called refcon. In fact -- let's see what Apple docs say about this callback:
refcon
The refcon passed into the original I/O request
My conclusion is that your code should read:
void USBDeviceReadCompletionCallback(void *refCon, IOReturn result, void *messageArg)
{
NSTextField *printerOutput = (__bridge NSTextField *) refCon; // <=== the change is here
NSLog(#"_printerOutput pointer = %p", printerOutput);
}
Can you, please, try this out? I get a feeling that you didn't try this.
Small but possibly important digression: Were it some other object, and if you didn't use ARC, I'd suggest retaining the _printerOutput variable when passing it into ReadPipeAsyncTO, and releasing it in the callback.
But, since the text field should, presumably, have the lifetime of the application, there is probably no need to do so.
ARC probably loses track of the need for the object behind the pointer to exist once it's passed into C code, but it doesn't matter, since the pointer is still stored in the printerOutput property. Besides, once a pointer is in C code, nothing can just "follow it around" and "reset it".
Confusion when it comes to understanding and explaining the concepts is precisely why I said "avoid ARC with sensitive code". :-)

Is there anything wrong with this pattern for a JS library?

I admittedly know little about the inner workings of javascript, but need to make a library and would like to learn (hence asking here). I understand using the closure and exporting to window to not pollute the global namespace, but beyond that it confuses me a bit.
(function() {
var Drop = window.Drop = function() {
var files = [];
var add = function(word) {
files.push(word);
return files;
}
return {
files: files,
add: add
}
}
})()
// All of these seem to be the same?
var a = Drop();
var b = new Drop();
var c = new Drop;
// Each has their own state which is what I want.
a.add("file1");
b.add("file2");
c.add("file3");
Why are all three ways of "initializing" Drop the same?
What exactly gives them the ability to have their own state?
Is there an alternative to the return syntax to export those functions on Drop?
Is there just a flat out better best practice way of creating a self contained library like this?
I have searched around the net, but have found very little consistency on this subject.
The first way (Drop()) just calls the function as normal, so this is the global object (window in browser environments). It does its stuff and then returns an object, as you'd expect.
The second way (new Drop()) creates a new Drop object and executes the constructor with this set to that object. You do not, however, use this anywhere and return an object created from an object literal, so the Drop object is discarded and the object literal returned instead.
The third way (new Drop) is semantically the same as the second; it is only a syntactic difference.
They all have their own state because each time you call Drop, it has its own set of local variables distinct from the local variables of any other call to Drop.
You could transform your code to use the normal new syntax and prototypes. This has a few advantages: namely, you only create the add function once rather than one for each Drop call. Your modified code might look like this:
function Drop() {
this.files = [];
}
Drop.prototype.add = function(word) {
this.files.push(word);
return this.files;
};
By doing this, though, you lose being able to call it without new. There is, however, a workaround: You can add this as the first line inside function Drop:
if(!(this instanceof Drop)) {
return new Drop();
}
Since when you call it with new, this will be a Drop, and when you call it without new, this will be something other than a Drop, you can see if this is a Drop, and if it is, continue initializing; otherwise, reinvoke it with new.
There is also another semantic difference. Consider the following code:
var drop = new Drop();
var adder = drop.add;
adder(someFile);
Your code will work here. The prototype-based code will not, since this will be the global object, not drop. This, too, has a workaround: somewhere in your constructor, you can do this:
this.add = this.add.bind(this);
Of course, if your library's consumers are not going to pull the function out of the object, you won't need to do this. Furthermore, you might need to shim Function.prototype.bind for browsers that don't have it.
No. It's all a matter of taste.
Why are all three ways of "initializing" Drop the same?
// All of these seem to be the same?
var a = Drop();
var b = new Drop();
var c = new Drop;
When you use new in JavaScript to invoke a function, the value of this inside the function becomes the new object.
But the reason they're the same in your case is that you're not using this at all. You're making a separate object using object literal syntax, and returning it instead, so the new has no impact.
What exactly gives them the ability to have their own state?
Because each function invocation makes a new object, each object is entirely different for each invocation.
The functions assigned to the object are recreated in each Drop invocation, and therefore create a closure over the enclosing variable scope. As such, the files array of each invocation is continuously accessible to the functions made in each respective invocation.
Is there an alternative to the return syntax to export those functions on Drop?
Yes. Assign the functions and array to this, and remove the return statement. But that will require the use of new. Alternatively, put the functions on the .prototype object of Drop, and they'll be shared among all instances made using new, but keep the array assigned to this in the constructor so that it's not shared.
For the prototyped functions to reference the array, they would use this.files.
Is there just a flat out better best practice way of creating a self contained library like this?
JavaScript is very flexible. There are many ways to approach a single problem, each with its own advantages/disadvantages. Generally it'll boil down to taking advantage of closures, of prototypal inheritance, or some combination of both.
Here's a full prototypal inheritance version. Also, the outer (function() {})() isn't being used, so I'm going to add a variable to take advantage of it.
(function() {
var totalObjects = 0; // visible only to functions created in this scope
var Drop = window.Drop = function() {
this.files = [];
this.serialNumber = totalObjects++;
}
Drop.prototype.add = function(word) {
this.files.push(word);
return this.files;
};
})();

Resources