Search Results

Search found 3389 results on 136 pages for 'const'.

Page 5/136 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • When should a member function have a const qualifier and when shouldn't it?

    - by SCFrench
    About six years ago, a software engineer named Harri Porten wrote this article, asking the question, "When should a member function have a const qualifier and when shouldn't it?" I found it to be the best write-up I could find of the issue, which I've been wrestling with more recently and which I think is not well covered in most discussions I've found on const correctness. Since a software information-sharing site as powerful as SO didn't exist back then, I'd like to resurrect the question here.

    Read the article

  • How to return a const QString reference in case of failure?

    - by moala
    Hi, consider the following code: const QString& MyClass::getID(int index) const { if (i < myArraySize && myArray[i]) { return myArray[i]->id; // id is a QString } else { return my_global_empty_qstring; // is a global empty QString } } How can I avoid to have an empty QString without changing the return type of the method? (It seems that returning an empty QString allocated on the stack is a bad idea) Thanks.

    Read the article

  • How can I get the following compiled on UVA?

    - by Michael Tsang
    Note the comment below. It cannot compiled on UVA because of a bug in GCC. #include <cstdio> #include <cstring> #include <cctype> #include <map> #include <stdexcept> class Board { public: bool read(FILE *); enum Colour {none, white, black}; Colour check() const; private: struct Index { size_t x; size_t y; Index &operator+=(const Index &) throw(std::range_error); Index operator+(const Index &) const throw(std::range_error); }; const static std::size_t size = 8; char data[size][size]; // Cannot be compiled on GCC 4.1.2 due to GCC bug 29993 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29993 typedef bool CheckFunction(Colour, const Index &) const; CheckFunction pawn, knight, bishop, king, rook; bool queen(const Colour c, const Index &location) const { return rook(c, location) || bishop(c, location); } static char get_king(Colour c) { return c == white ? 'k' : 'K'; } template<std::size_t n> bool check_consecutive(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; for(; data[target.x][target.y] == '.'; target += *p) { } if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } template<std::size_t n> bool check_distinct(Colour c, const Index &location, const Index (&offsets)[n]) const { for(const Index *p = offsets; p != (&offsets)[1]; ++p) { try { Index target = location + *p; if(data[target.x][target.y] == get_king(c)) return true; } catch(std::range_error &) { } } return false; } }; int main() { Board board; for(int d = 1; board.read(stdin); ++d) { Board::Colour c = board.check(); const char *sp; switch(c) { case Board::black: sp = "white"; break; case Board::white: sp = "black"; break; case Board::none: sp = "no"; break; } std::printf("Game #%d: %s king is in check.\n", d, sp); std::getchar(); // discard empty line } } bool Board::read(FILE *f) { static const char empty[] = "........" "........" "........" "........" "........" "........" "........" "........"; // 64 dots for(char (*p)[size] = data; p != (&data)[1]; ++p) { std::fread(*p, size, 1, f); std::fgetc(f); // discard new-line } return std::memcmp(empty, data, sizeof data); } Board::Colour Board::check() const { std::map<char, CheckFunction Board::*> fp; fp['P'] = &Board::pawn; fp['N'] = &Board::knight; fp['B'] = &Board::bishop; fp['Q'] = &Board::queen; fp['K'] = &Board::king; fp['R'] = &Board::rook; for(std::size_t i = 0; i != size; ++i) { for(std::size_t j = 0; j != size; ++j) { CheckFunction Board::* p = fp[std::toupper(data[i][j])]; if(p) { Colour ret; if(std::isupper(data[i][j])) ret = white; else ret = black; if((this->*p)(ret, (Index){i, j}/* C99 extension */)) return ret; } } } return none; } bool Board::pawn(const Colour c, const Index &location) const { const std::ptrdiff_t sh = c == white ? -1 : 1; const Index offsets[] = { {sh, 1}, {sh, -1} }; return check_distinct(c, location, offsets); } bool Board::knight(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2} }; return check_distinct(c, location, offsets); } bool Board::bishop(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 1}, {1, -1}, {-1, -1}, {-1, 1} }; return check_consecutive(c, location, offsets); } bool Board::rook(const Colour c, const Index &location) const { static const Index offsets[] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} }; return check_consecutive(c, location, offsets); } bool Board::king(const Colour c, const Index &location) const { static const Index offsets[] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1} }; return check_distinct(c, location, offsets); } Board::Index &Board::Index::operator+=(const Index &rhs) throw(std::range_error) { if(x + rhs.x >= size || y + rhs.y >= size) throw std::range_error("result is larger than size"); x += rhs.x; y += rhs.y; return *this; } Board::Index Board::Index::operator+(const Index &rhs) const throw(std::range_error) { Index ret = *this; return ret += rhs; }

    Read the article

  • Is it undefined behavior in the case of the private functions call in the initializer list?

    - by Alexey Malistov
    Consider the following code: struct Calc { Calc(const Arg1 & arg1, const Arg2 & arg2, /* */ const ArgN & argn) : arg1(arg1), arg2(arg2), /* */ argn(argn), coef1(get_coef1()), coef2(get_coef2()) { } int Calc1(); int Calc2(); int Calc3(); private: const Arg1 & arg1; const Arg2 & arg2; // ... const ArgN & argn; const int coef1; // I want to use const because const int coef2; // no modification is needed. int get_coef1() const { // calc coef1 using arg1, arg2, ..., argn; // undefined behavior? } int get_coef2() const { // calc coef2 using arg1, arg2, ..., argn and coef1; // undefined behavior? } }; struct Calc is not completely defined when I call get_coef1 and get_coef2 Is this code valid? Can I get UB?

    Read the article

  • Please help with C++ syntax for const accessor by reference.

    - by Hamish Grubijan
    Right not my implementation returns the thing by value. The member m_MyObj itself is not const - it's value changes depending on what the user selects with a Combo Box. I am no C++ guru, but I want to do this right. If I simply stick a & in front of GetChosenSourceSystem in both decl. and impl., I get one sort of compiler error. If I do one but not another - another error. If I do return &m_MyObj;. I will not list the errors here for now, unless there is a strong demand for it. I assume that an experienced C++ coder can tell what is going on here. I could omit constness or reference, but I want to make it tight and learn in the process as well. Thanks! // In header file MyObj GetChosenThingy() const; // In Implementation file. MyObj MyDlg::GetChosenThingy() const { return m_MyObj; }

    Read the article

  • Any problems with this C++ const reference accessor interface idiom?

    - by mskfisher
    I was converting a struct to a class so I could enforce a setter interface for my variables. I did not want to change all of the instances where the variable was read, though. So I converted this: struct foo_t { int x; float y; }; to this: class foo_t { int _x; float _y; public: foot_t() : x(_x), y(_y) { set(0, 0.0); } const int &x; const float &y; set(int x, float y) { _x = x; _y = y; } }; I'm interested in this because it seems to model C#'s idea of public read-only properties. Compiles fine, and I haven't seen any problems yet. Besides the boilerplate of associating the const references in the constructor, what are the downsides to this method? Any strange aliasing issues? Why haven't I seen this idiom before?

    Read the article

  • Do I need to store a generic rotation point/radius for rotating around a point other than the origin for object transforms?

    - by Casey
    I'm having trouble implementing a non-origin point rotation. I have a class Transform that stores each component separately in three 3D vectors for position, scale, and rotation. This is fine for local rotations based on the center of the object. The issue is how do I determine/concatenate non-origin rotations in addition to origin rotations. Normally this would be achieved as a Transform-Rotate-Transform for the center rotation followed by a Transform-Rotate-Transform for the non-origin point. The problem is because I am storing the individual components, the final Transform matrix is not calculated until needed by using the individual components to fill an appropriate Matrix. (See GetLocalTransform()) Do I need to store an additional rotation (and radius) for world rotations as well or is there a method of implementation that works while only using the single rotation value? Transform.h #ifndef A2DE_CTRANSFORM_H #define A2DE_CTRANSFORM_H #include "../a2de_vals.h" #include "CMatrix4x4.h" #include "CVector3D.h" #include <vector> A2DE_BEGIN class Transform { public: Transform(); Transform(Transform* parent); Transform(const Transform& other); Transform& operator=(const Transform& rhs); virtual ~Transform(); void SetParent(Transform* parent); void AddChild(Transform* child); void RemoveChild(Transform* child); Transform* FirstChild(); Transform* LastChild(); Transform* NextChild(); Transform* PreviousChild(); Transform* GetChild(std::size_t index); std::size_t GetChildCount() const; std::size_t GetChildCount(); void SetPosition(const a2de::Vector3D& position); const a2de::Vector3D& GetPosition() const; a2de::Vector3D& GetPosition(); void SetRotation(const a2de::Vector3D& rotation); const a2de::Vector3D& GetRotation() const; a2de::Vector3D& GetRotation(); void SetScale(const a2de::Vector3D& scale); const a2de::Vector3D& GetScale() const; a2de::Vector3D& GetScale(); a2de::Matrix4x4 GetLocalTransform() const; a2de::Matrix4x4 GetLocalTransform(); protected: private: a2de::Vector3D _position; a2de::Vector3D _scale; a2de::Vector3D _rotation; std::size_t _curChildIndex; Transform* _parent; std::vector<Transform*> _children; }; A2DE_END #endif Transform.cpp #include "CTransform.h" #include "CVector2D.h" #include "CVector4D.h" A2DE_BEGIN Transform::Transform() : _position(), _scale(1.0, 1.0), _rotation(), _curChildIndex(0), _parent(nullptr), _children() { /* DO NOTHING */ } Transform::Transform(Transform* parent) : _position(), _scale(1.0, 1.0), _rotation(), _curChildIndex(0), _parent(parent), _children() { /* DO NOTHING */ } Transform::Transform(const Transform& other) : _position(other._position), _scale(other._scale), _rotation(other._rotation), _curChildIndex(0), _parent(other._parent), _children(other._children) { /* DO NOTHING */ } Transform& Transform::operator=(const Transform& rhs) { if(this == &rhs) return *this; this->_position = rhs._position; this->_scale = rhs._scale; this->_rotation = rhs._rotation; this->_curChildIndex = 0; this->_parent = rhs._parent; this->_children = rhs._children; return *this; } Transform::~Transform() { _children.clear(); _parent = nullptr; } void Transform::SetParent(Transform* parent) { _parent = parent; } void Transform::AddChild(Transform* child) { if(child == nullptr) return; _children.push_back(child); } void Transform::RemoveChild(Transform* child) { if(_children.empty()) return; _children.erase(std::remove(_children.begin(), _children.end(), child), _children.end()); } Transform* Transform::FirstChild() { if(_children.empty()) return nullptr; return *(_children.begin()); } Transform* Transform::LastChild() { if(_children.empty()) return nullptr; return *(_children.end()); } Transform* Transform::NextChild() { if(_children.empty()) return nullptr; std::size_t s(_children.size()); if(_curChildIndex >= s) { _curChildIndex = s; return nullptr; } return _children[_curChildIndex++]; } Transform* Transform::PreviousChild() { if(_children.empty()) return nullptr; if(_curChildIndex == 0) { return nullptr; } return _children[_curChildIndex--]; } Transform* Transform::GetChild(std::size_t index) { if(_children.empty()) return nullptr; if(index > _children.size()) return nullptr; return _children[index]; } std::size_t Transform::GetChildCount() const { if(_children.empty()) return 0; return _children.size(); } std::size_t Transform::GetChildCount() { return static_cast<const Transform&>(*this).GetChildCount(); } void Transform::SetPosition(const a2de::Vector3D& position) { _position = position; } const a2de::Vector3D& Transform::GetPosition() const { return _position; } a2de::Vector3D& Transform::GetPosition() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetPosition()); } void Transform::SetRotation(const a2de::Vector3D& rotation) { _rotation = rotation; } const a2de::Vector3D& Transform::GetRotation() const { return _rotation; } a2de::Vector3D& Transform::GetRotation() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetRotation()); } void Transform::SetScale(const a2de::Vector3D& scale) { _scale = scale; } const a2de::Vector3D& Transform::GetScale() const { return _scale; } a2de::Vector3D& Transform::GetScale() { return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetScale()); } a2de::Matrix4x4 Transform::GetLocalTransform() const { Matrix4x4 p((_parent ? _parent->GetLocalTransform() : a2de::Matrix4x4::GetIdentity())); Matrix4x4 t(a2de::Matrix4x4::GetTranslationMatrix(_position)); Matrix4x4 r(a2de::Matrix4x4::GetRotationMatrix(_rotation)); Matrix4x4 s(a2de::Matrix4x4::GetScaleMatrix(_scale)); return (p * t * r * s); } a2de::Matrix4x4 Transform::GetLocalTransform() { return static_cast<const Transform&>(*this).GetLocalTransform(); } A2DE_END

    Read the article

  • Converting String^ and Collection of String^ to const char*

    - by Jim Jones
    Using VS2008 Managed C++ to wrap a dll. The native method takes a series of single const char* values and a collection of char* values. Going to make an example function: Function1(char * value1, TF_StringList& catList); TF_StringList is a dll class with 3 insert methods, the one I want to use is: TF_StringList::insert(const char* str); So I set up a wrapper method of: WrapperClass::callFunction(String^ mvalue1, ArrayList mcatList); mvalue1 is converted to const char* using: const char* value1 = (char*)(Marshal::StringToHGlobalAnsi(mvalue1)).ToPointer(); However, when a get to the collection of strings, I iterate over it getting each string using the index: String^ mstr = mcatList[i]; Have tried every way of converting String^ to const char* and in every case the TF_StringList::insert(const char* str) method throws a C2663 error which has to do with the const-ness of the value. What is the problem?

    Read the article

  • Why can't I access a const vector with iterator?

    - by tsubasa
    My example is as below. I found out the problem is with "const" in function void test's parameter. I don't know why the compiler does not allow. Could anybody tell me? Thanks. vector<int> p; void test(const vector<int> &blah) { vector<int>::iterator it; for (it=blah.begin(); it!=blah.end(); it++) { cout<<*it<<" "; } } int main() { p.push_back(1); p.push_back(2); p.push_back(3); test(p); return 0; }

    Read the article

  • 'array bound is not an integer constant' when defining size of array in class, using an element of a const array

    - by user574733
    #ifndef QWERT_H #define QWERT_H const int x [] = {1, 2,}; const int z = 3; #endif #include <iostream> #include "qwert.h" class Class { int y [x[0]]; //error:array bound is not an integer constant int g [z]; //no problem }; int main () { int y [x[0]]; //no problem Class a_class; } I can't figure out why this doesn't work. Other people with this problem seem to be trying to dynamically allocate arrays. Any help is much appreciated.

    Read the article

  • Why do some people prefer "T const&" over "const T&"?

    - by Michael Aaron Safyan
    So, I realize that const T& and T const& are identical and both mean a reference to a const T. In both cases, the reference is also constant (references cannot be reassigned, unlike pointers). I've observed, in my somewhat limited experience, that most C++ programmers use const T&, but I have come across a few people who use T const&. Is this just a personal preference? Why is one chosen over the other?

    Read the article

  • How can I pass a const array or a variable array to a function in C?

    - by CSharperWithJava
    I have a simple function Bar that uses a set of values from a data set that is passed in in the form of an Array of data structures. The data can come from two sources: a constant initialized array of default values, or a dynamically updated cache. The calling function determines which data is used and should be passed to Bar. Bar doesn't need to edit any of the data and in fact should never do so. How should I declare Bar's data parameter so that I can provide data from either set? union Foo { long _long; int _int; } static const Foo DEFAULTS[8] = {1,10,100,1000,10000,100000,1000000,10000000}; static Foo Cache[8] = {0}; void Bar(Foo* dataSet, int len);//example function prototype Note, this is C, NOT C++ if that makes a difference; Edit Oh, one more thing. When I use the example prototype I get a type qualifier mismatch warning, (because I'm passing a mutable reference to a const array?). What do I have to change for that?

    Read the article

  • Problems extracting information from RSS feed description field

    - by Graeme
    Hi, I've built an iPhone application using the parsing code from the TopSongs sample iPhone application. I've hit a problem though - the feed I'm trying to parse data from doesn't have a separate field for every piece of information (i.e. if it was for a feed about dogs, all the information such as dog type, dog age and dog price is contained in the feed. However, the TopSongs app relies on information having its own tags, so instead of using it uses and . So my question is this. How do I extract this information from the description field so that it can be parsed using the TopSongs parser? Can you somehow extract the dog age, price and type information using Yahoo Pipes and use that RSS feed for the feed? Or is there code that I can add to do it in application? Update: To view the code of my application parser (based on the TopSongs Core Data Apple provided application, see below. Here's a sample of one item from the the actual RSS feed I'm using (the description is longer, and has status,size, and a couple of other fields, but they're all formatted the same.: <item> <title>MOE, MARGRET STREET</title> <description> <b>District/Region:</b>&nbsp;REGION 09</br><b>Location:</b>&nbsp;MOE</br><b>Name:</b>&nbsp;MARGRET STREET</br></description> <pubDate>Thu,11 Mar 2010 05:43:03 GMT</pubDate> <guid>1266148</guid> </item> /* File: iTunesRSSImporter.m Abstract: Downloads, parses, and imports the iTunes top songs RSS feed into Core Data. Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2009 Apple Inc. All Rights Reserved. */ #import "iTunesRSSImporter.h" #import "Song.h" #import "Category.h" #import "CategoryCache.h" #import <libxml/tree.h> // Function prototypes for SAX callbacks. This sample implements a minimal subset of SAX callbacks. // Depending on your application's needs, you might want to implement more callbacks. static void startElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); static void endElementSAX(void *context, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); static void charactersFoundSAX(void *context, const xmlChar *characters, int length); static void errorEncounteredSAX(void *context, const char *errorMessage, ...); // Forward reference. The structure is defined in full at the end of the file. static xmlSAXHandler simpleSAXHandlerStruct; // Class extension for private properties and methods. @interface iTunesRSSImporter () @property BOOL storingCharacters; @property (nonatomic, retain) NSMutableData *characterBuffer; @property BOOL done; @property BOOL parsingASong; @property NSUInteger countForCurrentBatch; @property (nonatomic, retain) Song *currentSong; @property (nonatomic, retain) NSURLConnection *rssConnection; @property (nonatomic, retain) NSDateFormatter *dateFormatter; // The autorelease pool property is assign because autorelease pools cannot be retained. @property (nonatomic, assign) NSAutoreleasePool *importPool; @end static double lookuptime = 0; @implementation iTunesRSSImporter @synthesize iTunesURL, delegate, persistentStoreCoordinator; @synthesize rssConnection, done, parsingASong, storingCharacters, currentSong, countForCurrentBatch, characterBuffer, dateFormatter, importPool; - (void)dealloc { [iTunesURL release]; [characterBuffer release]; [currentSong release]; [rssConnection release]; [dateFormatter release]; [persistentStoreCoordinator release]; [insertionContext release]; [songEntityDescription release]; [theCache release]; [super dealloc]; } - (void)main { self.importPool = [[NSAutoreleasePool alloc] init]; if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] addObserver:delegate selector:@selector(importerDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } done = NO; self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; // necessary because iTunes RSS feed is not localized, so if the device region has been set to other than US // the date formatter must be set to US locale in order to parse the dates [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]]; self.characterBuffer = [NSMutableData data]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:iTunesURL]; // create the connection with the request and start loading the data rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // This creates a context for "push" parsing in which chunks of data that are not "well balanced" can be passed // to the context for streaming parsing. The handler structure defined above will be used for all the parsing. // The second argument, self, will be passed as user data to each of the SAX handlers. The last three arguments // are left blank to avoid creating a tree in memory. context = xmlCreatePushParserCtxt(&simpleSAXHandlerStruct, self, NULL, 0, NULL); if (rssConnection != nil) { do { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } while (!done); } // Display the total time spent finding a specific object for a relationship NSLog(@"lookup time %f", lookuptime); // Release resources used only in this thread. xmlFreeParserCtxt(context); self.characterBuffer = nil; self.dateFormatter = nil; self.rssConnection = nil; self.currentSong = nil; [theCache release]; theCache = nil; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); if (delegate && [delegate respondsToSelector:@selector(importerDidSave:)]) { [[NSNotificationCenter defaultCenter] removeObserver:delegate name:NSManagedObjectContextDidSaveNotification object:self.insertionContext]; } if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importerDidFinishParsingData:)]) { [self.delegate importerDidFinishParsingData:self]; } [importPool release]; self.importPool = nil; } - (NSManagedObjectContext *)insertionContext { if (insertionContext == nil) { insertionContext = [[NSManagedObjectContext alloc] init]; [insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return insertionContext; } - (void)forwardError:(NSError *)error { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(importer:didFailWithError:)]) { [self.delegate importer:self didFailWithError:error]; } } - (NSEntityDescription *)songEntityDescription { if (songEntityDescription == nil) { songEntityDescription = [[NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.insertionContext] retain]; } return songEntityDescription; } - (CategoryCache *)theCache { if (theCache == nil) { theCache = [[CategoryCache alloc] init]; theCache.managedObjectContext = self.insertionContext; } return theCache; } - (Song *)currentSong { if (currentSong == nil) { currentSong = [[Song alloc] initWithEntity:self.songEntityDescription insertIntoManagedObjectContext:self.insertionContext]; } return currentSong; } #pragma mark NSURLConnection Delegate methods // Forward errors to the delegate. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self performSelectorOnMainThread:@selector(forwardError:) withObject:error waitUntilDone:NO]; // Set the condition which ends the run loop. done = YES; } // Called when a chunk of data has been downloaded. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // Process the downloaded chunk of data. xmlParseChunk(context, (const char *)[data bytes], [data length], 0); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Signal the context that parsing is complete by passing "1" as the last parameter. xmlParseChunk(context, NULL, 0, 1); context = NULL; // Set the condition which ends the run loop. done = YES; } #pragma mark Parsing support methods static const NSUInteger kImportBatchSize = 20; - (void)finishedCurrentSong { parsingASong = NO; self.currentSong = nil; countForCurrentBatch++; // Periodically purge the autorelease pool and save the context. The frequency of this action may need to be tuned according to the // size of the objects being parsed. The goal is to keep the autorelease pool from growing too large, but // taking this action too frequently would be wasteful and reduce performance. if (countForCurrentBatch == kImportBatchSize) { [importPool release]; self.importPool = [[NSAutoreleasePool alloc] init]; NSError *saveError = nil; NSAssert1([insertionContext save:&saveError], @"Unhandled error saving managed object context in import thread: %@", [saveError localizedDescription]); countForCurrentBatch = 0; } } /* Character data is appended to a buffer until the current element ends. */ - (void)appendCharacters:(const char *)charactersFound length:(NSInteger)length { [characterBuffer appendBytes:charactersFound length:length]; } - (NSString *)currentString { // Create a string with the character data using UTF-8 encoding. UTF-8 is the default XML data encoding. NSString *currentString = [[[NSString alloc] initWithData:characterBuffer encoding:NSUTF8StringEncoding] autorelease]; [characterBuffer setLength:0]; return currentString; } @end #pragma mark SAX Parsing Callbacks // The following constants are the XML element names and their string lengths for parsing comparison. // The lengths include the null terminator, to ensure exact matches. static const char *kName_Item = "item"; static const NSUInteger kLength_Item = 5; static const char *kName_Title = "title"; static const NSUInteger kLength_Title = 6; static const char *kName_Category = "category"; static const NSUInteger kLength_Category = 9; static const char *kName_Itms = "itms"; static const NSUInteger kLength_Itms = 5; static const char *kName_Artist = "description"; static const NSUInteger kLength_Artist = 7; static const char *kName_Album = "description"; static const NSUInteger kLength_Album = 6; static const char *kName_ReleaseDate = "releasedate"; static const NSUInteger kLength_ReleaseDate = 12; /* This callback is invoked when the importer finds the beginning of a node in the XML. For this application, out parsing needs are relatively modest - we need only match the node name. An "item" node is a record of data about a song. In that case we create a new Song object. The other nodes of interest are several of the child nodes of the Song currently being parsed. For those nodes we want to accumulate the character data in a buffer. Some of the child nodes use a namespace prefix. */ static void startElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // The second parameter to strncmp is the name of the element, which we known from the XML schema of the feed. // The third parameter to strncmp is the number of characters in the element name, plus 1 for the null terminator. if (prefix == NULL && !strncmp((const char *)localname, kName_Item, kLength_Item)) { importer.parsingASong = YES; } else if (importer.parsingASong && ( (prefix == NULL && (!strncmp((const char *)localname, kName_Title, kLength_Title) || !strncmp((const char *)localname, kName_Category, kLength_Category))) || ((prefix != NULL && !strncmp((const char *)prefix, kName_Itms, kLength_Itms)) && (!strncmp((const char *)localname, kName_Artist, kLength_Artist) || !strncmp((const char *)localname, kName_Album, kLength_Album) || !strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate))) )) { importer.storingCharacters = YES; } } /* This callback is invoked when the parse reaches the end of a node. At that point we finish processing that node, if it is of interest to us. For "item" nodes, that means we have completed parsing a Song object. We pass the song to a method in the superclass which will eventually deliver it to the delegate. For the other nodes we care about, this means we have all the character data. The next step is to create an NSString using the buffer contents and store that with the current Song object. */ static void endElementSAX(void *parsingContext, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; if (importer.parsingASong == NO) return; if (prefix == NULL) { if (!strncmp((const char *)localname, kName_Item, kLength_Item)) { [importer finishedCurrentSong]; } else if (!strncmp((const char *)localname, kName_Title, kLength_Title)) { importer.currentSong.title = importer.currentString; } else if (!strncmp((const char *)localname, kName_Category, kLength_Category)) { double before = [NSDate timeIntervalSinceReferenceDate]; Category *category = [importer.theCache categoryWithName:importer.currentString]; double delta = [NSDate timeIntervalSinceReferenceDate] - before; lookuptime += delta; importer.currentSong.category = category; } } else if (!strncmp((const char *)prefix, kName_Itms, kLength_Itms)) { if (!strncmp((const char *)localname, kName_Artist, kLength_Artist)) { NSString *string = importer.currentSong.artist; NSArray *strings = [string componentsSeparatedByString: @", "]; //importer.currentSong.artist = importer.currentString; } else if (!strncmp((const char *)localname, kName_Album, kLength_Album)) { importer.currentSong.album = importer.currentString; } else if (!strncmp((const char *)localname, kName_ReleaseDate, kLength_ReleaseDate)) { NSString *dateString = importer.currentString; importer.currentSong.releaseDate = [importer.dateFormatter dateFromString:dateString]; } } importer.storingCharacters = NO; } /* This callback is invoked when the parser encounters character data inside a node. The importer class determines how to use the character data. */ static void charactersFoundSAX(void *parsingContext, const xmlChar *characterArray, int numberOfCharacters) { iTunesRSSImporter *importer = (iTunesRSSImporter *)parsingContext; // A state variable, "storingCharacters", is set when nodes of interest begin and end. // This determines whether character data is handled or ignored. if (importer.storingCharacters == NO) return; [importer appendCharacters:(const char *)characterArray length:numberOfCharacters]; } /* A production application should include robust error handling as part of its parsing implementation. The specifics of how errors are handled depends on the application. */ static void errorEncounteredSAX(void *parsingContext, const char *errorMessage, ...) { // Handle errors as appropriate for your application. NSCAssert(NO, @"Unhandled error encountered during SAX parse."); } // The handler struct has positions for a large number of callback functions. If NULL is supplied at a given position, // that callback functionality won't be used. Refer to libxml documentation at http://www.xmlsoft.org for more information // about the SAX callbacks. static xmlSAXHandler simpleSAXHandlerStruct = { NULL, /* internalSubset */ NULL, /* isStandalone */ NULL, /* hasInternalSubset */ NULL, /* hasExternalSubset */ NULL, /* resolveEntity */ NULL, /* getEntity */ NULL, /* entityDecl */ NULL, /* notationDecl */ NULL, /* attributeDecl */ NULL, /* elementDecl */ NULL, /* unparsedEntityDecl */ NULL, /* setDocumentLocator */ NULL, /* startDocument */ NULL, /* endDocument */ NULL, /* startElement*/ NULL, /* endElement */ NULL, /* reference */ charactersFoundSAX, /* characters */ NULL, /* ignorableWhitespace */ NULL, /* processingInstruction */ NULL, /* comment */ NULL, /* warning */ errorEncounteredSAX, /* error */ NULL, /* fatalError //: unused error() get all the errors */ NULL, /* getParameterEntity */ NULL, /* cdataBlock */ NULL, /* externalSubset */ XML_SAX2_MAGIC, // NULL, startElementSAX, /* startElementNs */ endElementSAX, /* endElementNs */ NULL, /* serror */ }; Thanks.

    Read the article

  • Const-correctness semantics in C++

    - by thirtythreeforty
    For fun and profit™, I'm writing a trie class in C++ (using the C++11 standard.) My trie<T> has an iterator, trie<T>::iterator. (They're all actually functionally const_iterators, because you cannot modify a trie's value_type.) The iterator's class declaration looks partially like this: template<typename T> class trie<T>::iterator : public std::iterator<std::bidirectional_iterator_tag, T> { friend class trie<T>; struct state { state(const trie<T>* const node, const typename std::vector<std::pair<typename T::value_type, std::unique_ptr<trie<T>>>>::const_iterator& node_map_it ) : node{node}, node_map_it{node_map_it} {} // This pointer is to const data: const trie<T>* node; typename std::vector<std::pair<typename T::value_type, std::unique_ptr<trie<T>>>>::const_iterator node_map_it; }; public: typedef const T value_type; iterator() =default; iterator(const trie<T>* node) { parents.emplace(node, node->children.cbegin()); // ... } // ... private: std::stack<state> parents; // ... }; Notice that the node pointer is declared const. This is because (in my mind) the iterator should not be modifying the node that it points to; it is just an iterator. Now, elsewhere in my main trie<T> class, I have an erase function that has a common STL signature--it takes an iterator to data to erase (and returns an iterator to the next object). template<typename T> typename trie<T>::iterator trie<T>::erase(const_iterator it) { // ... // Cannot modify a const object! it.parents.top().node->is_leaf = false; // ... } The compiler complains because the node pointer is read-only! The erase function definitely should modify the trie that the iterator points to, even though the iterator shouldn't. So, I have two questions: Should iterator's constructors be public? trie<T> has the necessary begin() and end() members, and of course trie<T>::iterator and trie<T> are mutual friends, but I don't know what the convention is. Making them private would solve a lot of the angst I'm having about removing the const "promise" from the iterator's constructor. What are the correct const semantics/conventions regarding the iterator and its node pointer here? Nobody has ever explained this to me, and I can't find any tutorials or articles on the Web. This is probably the more important question, but it does require a good deal of planning and proper implementation. I suppose it could be circumvented by just implementing 1, but it's the principle of the thing!

    Read the article

  • How to modify a given class to use const operators

    - by zsero
    I am trying to solve my question regarding using push_back in more than one level. From the comments/answers it is clear that I have to: Create a copy operator which takes a const argument Modify all my operators to const But because this header file is given to me there is an operator what I cannot make into const. It is a simple: float & operator [] (int i) { return _item[i]; } In the given program, this operator is used to get and set data. My problem is that because I need to have this operator in the header file, I cannot turn all the other operators to const, what means I cannot insert a copy operator. How can I make all my operators into const, while preserving the functionality of the already written program? Here is the full declaration of the class: class Vector3f { float _item[3]; public: float & operator [] (int i) { return _item[i]; } Vector3f(float x, float y, float z) { _item[0] = x ; _item[1] = y ; _item[2] = z; }; Vector3f() {}; Vector3f & operator = ( const Vector3f& obj) { _item[0] = obj[0]; _item[1] = obj[1]; _item[2] = obj[2]; return *this; }; Vector3f & operator += ( const Vector3f & obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return *this; }; bool operator ==( const Vector3f & obj) { bool x = (_item[0] == obj[0]) && (_item[1] == obj[1]) && (_item[2] == obj[2]); return x; } // my copy operator Vector3f(const Vector3f& obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return this; } };

    Read the article

  • Naming a typedef for a boost::shared_ptr<const Foo>

    - by Blair Zajac
    Silly question, but say you have class Foo: class Foo { public: typedef boost::shared_ptr<Foo> RcPtr; void non_const_method() {} void const_method() const {} }; Having a const Foo::RcPtr doesn't prevent non-const methods from being invoked on the class, the following will compile: #include <boost/shared_ptr.hpp> int main() { const Foo::RcPtr const_foo_ptr(new Foo); const_foo_ptr->non_const_method(); const_foo_ptr->const_method(); return 0; } But naming a typedef ConstRcPtr implies, to me, that the typedef would be typedef const boost::shared_ptr<Foo> ConstRcPtr; which is not what I'm interested in. An odder name, but maybe more accurate, is RcPtrConst: typedef boost::shared_ptr<const Foo> RcPtrConst; However, Googling for RcPtrConst gets zero hits, so people don't use this as a typedef name :) Does anyone have any other suggestions?

    Read the article

  • const read only local copies

    - by robUK
    Hello gcc 4.4.4 c89 I am just wondering is it worth passing a const into a function. i.e. void do_something(const char *dest, const int size) The size is a read-only so I don't want to change it. However, some developers never have this as const has it is a local copy that is being used. The pointer is const as you can change the value in the calling routine. I always have a const on read-only local copies, as it confirms to anyone reading my code that it is a read-only variable. And also, when coding I don't make the mistake of changing it without realizing. Many thanks for any suggestions,

    Read the article

  • c++ Using const in a copy constructor?

    - by Anton
    I have never written copy constructor, so in order to avoid pain i wanted to know if what i have coded is legit. It compiles but i am not sure that it works as a copy constructor should. Also do i have to use const in the copy constructor or i can simply drop it. (What i dont like about const is that the compiler cries if i use some non const functions). //EditNode.h class EditNode { explicit EditNode(QString elementName); EditNode(const EditNode &src); } //EditNodeContainer.h class EditNodeContainer : public EditNode { explicit EditNodeContainer(QString elementName); EditNodeContainer(const EditNodeContainer &src); } //EditNodeContainer.cpp EditNodeContainer::EditNodeContainer(QString elementName):EditNode(elementName) { } //This seems to compile but not sure if it works EditNodeContainer::EditNodeContainer(const EditNodeContainer &src):EditNode(src) { } //the idea whould be to do something like this EditNodeContainer *container1 = new EditNodeContainer("c1"); EditNodeContainer *copyContainer = new EditNodeContainer(container1);

    Read the article

  • Parameter passed by const reference returned by const reference.

    - by Alien01
    Hello, I was reading C++ Faq Second Edition , faq number 32.08 . FAQ says that parameter passed by const reference and returned by const reference can cause dangling reference. But it is ok if parameter is passed by reference and returned by reference. I got it that it is unsafe in case of const reference but how is it safe in case when parameter is non const reference. Last line of FAQ says "Note that if a function accepts a parameter by non-const reference (for example, f(string& s)), returning a copy of this reference parameter is safe because a temporary cannot be passed by non-const reference." Need some insight on this!!

    Read the article

  • const ready only local copies

    - by robUK
    Hello gcc 4.4.4 c89 I am just wondering is it worth passing a const into a function. i.e. void do_something(const char *dest, const int size) The size is a ready-only so I don't want to change it. However, some developers never have this as const has it is a local copy that is being used. The pointer is const as you can change the value in the calling routine. I always have a const on ready-only local copies, as it confirms to anyone reading my code that it is a ready-only variable. And also, when coding I don't make the mistake of changing it without realizing. Many thanks for any suggestions,

    Read the article

  • C++ Template const char array to int

    - by Levi Schuck
    So, I'm wishing to be able to have a static const compile time struct that holds some value based on a string by using templates. I only desire up to four characters. I know that the type of 'abcd' is int, and so is 'ab','abc', and although 'a' is of type char, it works out for a template<int v> struct What I wish to do is take sizes of 2,3,4,5 of some const char, "abcd" and have the same functionality as if they used 'abcd'. Note that I do not mean 1,2,3, or 4 because I expect the null terminator. cout << typeid("abcd").name() << endl; tells me that the type for this hard coded string is char const [5], which includes the null terminator on the end. I understand that I will need to twiddle the values as characters, so they are represented as an integer. I cannot use constexpr since VS10 does not support it (VS11 doesn't either..) So, for example with somewhere this template defined, and later the last line template <int v> struct something { static const int value = v; }; //Eventually in some method cout << typeid(something<'abcd'>::value).name() << endl; works just fine. I've tried template<char v[5]> struct something2 { static const int value = v[0]; } template<char const v[5]> struct something2 { static const int value = v[0]; } template<const char v[5]> struct something2 { static const int value = v[0]; } All of them build individually, though when I throw in my test, cout << typeid(something2<"abcd">::value).name() << endl; I get 'something2' : invalid expression as a template argument for 'v' 'something2' : use of class template requires template argument list Is this not feasible or am I misunderstanding something?

    Read the article

  • How to initialize a static const map in c++?

    - by Meloun
    Hi, I need just dictionary or asociative array string = int. There is type map C++ for this case. But I need make one map in my class make for all instances(- static) and this map cannot be changed(- const); I have found this way with boost library std::map<int, char> example = boost::assign::map_list_of(1, 'a') (2, 'b') (3, 'c'); Is there other solution without this lib? I have tried something like this, but there are always some issues with map initialization. class myClass{ private: static map<int,int> create_map() { map<int,int> m; m[1] = 2; m[3] = 4; m[5] = 6; return m; } static map<int,int> myMap = create_map(); } thanks

    Read the article

  • Make All Types Constant by Default in C++

    - by Jon Purdy
    What is the simplest and least obtrusive way to indicate to the compiler, whether by means of compiler options, #defines, typedefs, or templates, that every time I say T, I really mean T const? I would prefer not to make use of an external preprocessor. Since I don't use the mutable keyword, that would be acceptable to repurpose to indicate mutable state. Potential (suboptimal) solutions so far: // I presume redefinition of keywords is implementation-defined or illegal. #define int int const #define ptr * const int i(0); int ptr j(&i); typedef int const Int; typedef int const* const Intp; Int i(0); Intp j(&i); template<class T> struct C { typedef T const type; typedef T const* const ptr; }; C<int>::type i(0); C<int>::ptr j(&i);

    Read the article

  • Const references when dereferencing iterator on set, starting from Visual Studio 2010

    - by Patrick
    Starting from Visual Studio 2010, iterating over a set seems to return an iterator that dereferences the data as 'const data' instead of non-const. The following code is an example of something that does compile on Visual Studio 2005, but not on 2010 (this is an artificial example, but clearly illustrates the problem we found on our own code). In this example, I have a class that stores a position together with a temperature. I define comparison operators (not all them, just enough to illustrate the problem) that only use the position, not the temperature. The point is that for me two instances are identical if the position is identical; I don't care about the temperature. #include <set> class DataPoint { public: DataPoint (int x, int y) : m_x(x), m_y(y), m_temperature(0) {} void setTemperature(double t) {m_temperature = t;} bool operator<(const DataPoint& rhs) const { if (m_x==rhs.m_x) return m_y<rhs.m_y; else return m_x<rhs.m_x; } bool operator==(const DataPoint& rhs) const { if (m_x!=rhs.m_x) return false; if (m_y!=rhs.m_y) return false; return true; } private: int m_x; int m_y; double m_temperature; }; typedef std::set<DataPoint> DataPointCollection; void main(void) { DataPointCollection points; points.insert (DataPoint(1,1)); points.insert (DataPoint(1,1)); points.insert (DataPoint(1,2)); points.insert (DataPoint(1,3)); points.insert (DataPoint(1,1)); for (DataPointCollection::iterator it=points.begin();it!=points.end();++it) { DataPoint &point = *it; point.setTemperature(10); } } In the main routine I have a set to which I add some points. To check the correctness of the comparison operator, I add data points with the same position multiple times. When writing the contents of the set, I can clearly see there are only 3 points in the set. The for-loop loops over the set, and sets the temperature. Logically this is allowed, since the temperature is not used in the comparison operators. This code compiles correctly in Visual Studio 2005, but gives compilation errors in Visual Studio 2010 on the following line (in the for-loop): DataPoint &point = *it; The error given is that it can't assign a "const DataPoint" to a [non-const] "DataPoint &". It seems that you have no decent (= non-dirty) way of writing this code in VS2010 if you have a comparison operator that only compares parts of the data members. Possible solutions are: Adding a const-cast to the line where it gives an error Making temperature mutable and making setTemperature a const method But to me both solutions seem rather 'dirty'. It looks like the C++ standards committee overlooked this situation. Or not? What are clean solutions to solve this problem? Did some of you encounter this same problem and how did you solve it? Patrick

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >