Search Results

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

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

  • int vs const int&

    - by Valdo
    I've noticed that I usually use constant references as return values or arguments. I think the reason is that it works almost the same as using non-reference in the code. But it definitely takes more space and function declarations become longer. I'm OK with such code but I think some people my find it a bad programming style. What do you think? Is it worth writing const int& over int? I think it's optimized by the compiler anyway, so maybe I'm just wasting my time coding it, a?

    Read the article

  • Why isn't the compiler smarter in this const function overloading problem?

    - by Frank
    The following code does not compile: #include <iostream> class Foo { std::string s; public: const std::string& GetString() const { return s; } std::string* GetString() { return &s; } }; int main(int argc, char** argv){ Foo foo; const std::string& s = foo.GetString(); // error return 0; } I get the following error: const1.cc:11: error: invalid initialization of reference of type 'const std::string&' from expression of type 'std::string* It does make some sense because foo is not of type const Foo, but just Foo, so the compiler wants to use the non-const function. But still, why can't it recognize that I want to call the const GetString function, by looking at the (type of) variable I assign it to? I found this kind of surprising.

    Read the article

  • DLL Exports: not all my functions are exported

    - by carmellose
    I'm trying to create a Windows DLL which exports a number of functions, howver all my functions are exported but one !! I can't figure it out. The macro I use is this simple one : __declspec(dllexport) void myfunction(); It works for all my functions except one. I've looked inside Dependency Walker and here they all are, except one. How can that be ? What would be the cause for that ? I'm stuck. Edit: to be more precise, here is the function in the .h : namespace my { namespace great { namespace namespaaace { __declspec(dllexport) void prob_dump(const char *filename, const double p[], int nx, const double Q[], const double xlow[], const char ixlow[], const double xupp[], const char ixupp[], const double A[], int my, const double bA[], const double C[], int mz, const double clow[], const char iclow[], const double cupp[], const char icupp[] ); }}} And in the .cpp file it goes like this: namespace my { namespace great { namespace namespaaace { namespace { void dump_mtx(std::ostream& ostr, const double *mtx, int rows, int cols, const char *ind = 0) { /* some random code there, nothing special, no statics whatsoever */ } } // end anonymous namespace here // dump the problem specification into a file void prob_dump( const char *filename, const double p[], int nx, const double Q[], const double xlow[], const char ixlow[], const double xupp[], const char ixupp[], const double A[], int my, const double bA[], const double C[], int mz, const double clow[], const char iclow[], const double cupp[], const char icupp[] ) { std::ofstream fout; fout.open(filename, std::ios::trunc); /* implementation there */ dump_mtx(fout, Q, nx, nx); } }}} Thanks

    Read the article

  • return value (not a reference) from the function, bound to a const reference in the calling function

    - by brainydexter
    "If you return a value (not a reference) from the function, then bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function." So: const BoundingBox Player::GetBoundingBox(void) { return BoundingBox( &GetBoundingSphere() ); } Returns a value of type const BoundingBox from function GetBoundingBox() Called function: (From within function Update() the following is called:) variant I: (Bind it to a const reference) const BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox(); variant II: (Bind it to a const copy) const BoundingBox l_Bbox = l_pPlayer->GetBoundingBox(); Both work fine and I don't see the l_Bbox object going out of scope. (Though, I understand in variant one, the copy constructor is not called and thus is slightly better than variant II). Also, for comparison, I made the following changes. BoundingBox Player::GetBoundingBox(void) { return BoundingBox( &GetBoundingSphere() ); } with Variants: I BoundingBox& l_Bbox = l_pPlayer->GetBoundingBox(); and II: BoundingBox l_Bbox = l_pPlayer->GetBoundingBox(); The objet l_Bbox still does not out scope. So, I don't see how "bind it to a const reference in the calling function, its lifetime would be extended to the scope of the calling function", really extends the lifetime of the object to the scope of the calling function ? Am I missing something trivial here..please explain .. Thanks a lot

    Read the article

  • std::map for storing static const Objects

    - by Sean M.
    I am making a game similar to Minecraft, and I am trying to fine a way to keep a map of Block objects sorted by their id. This is almost identical to the way that Minecraft does it, in that they declare a bunch of static final Block objects and initialize them, and then the constructor of each block puts a reference of that block into whatever the Java equivalent of a std::map is, so there is a central place to get ids and the Blocks with those ids. The problem is, that I am making my game in C++, and trying to do the exact same thing. In Block.h, I am declaring the Blocks like so: //Block.h public: static const Block Vacuum; static const Block Test; And in Block.cpp I am initializing them like so: //Block.cpp const Block Block::Vacuum = Block("Vacuum", 0, 0); const Block Block::Test = Block("Test", 1, 0); The block constructor looks like this: Block::Block(std::string name, uint16 id, uint8 tex) { //Check for repeat ids if (IdInUse(id)) { fprintf(stderr, "Block id %u is already in use!", (uint32)id); throw std::runtime_error("You cannot reuse block ids!"); } _id = id; //Check for repeat names if (NameInUse(name)) { fprintf(stderr, "Block name %s is already in use!", name); throw std::runtime_error("You cannot reuse block names!"); } _name = name; _tex = tex; //fprintf(stdout, "Using texture %u\n", _tex); _transparent = false; _solidity = 1.0f; idMap[id] = this; nameMap[name] = this; } And finally, the maps that I'm using to store references of Blocks in relation to their names and ids are declared as such: std::map<uint16, Block*> Block::idMap = std::map<uint16, Block*>(); //The map of block ids std::map<std::string, Block*> Block::nameMap = std::map<std::string, Block*>(); //The map of block names The problem comes when I try to get the Blocks in the maps using a method called const Block* GetBlock(uint16 id), where the last line is return idMap.at(id);. This line returns a Block with completely random values like _visibility = 0xcccc and such like that, found out through debugging. So my question is, is there something wrong with the blocks being declared as const obejcts, and then stored at pointers and accessed later on? The reason I cant store them as Block& is because that makes a copy of the Block when it is entered, so the block wouldn't have any of the attributes that could be set afterwards in the constructor of any child class, so I think I need to store them as a pointer. Any help is greatly appreciated, as I don't fully understand pointers yet. Just ask if you need to see any other parts of the code.

    Read the article

  • Dynamic allocating of const member structures

    - by Willy
    I've got class which is using plain-only-data struct with const variables and I'm not sure, if I'm allocating these structures in a proper way. It looks more or less like: #include <cstdlib> #include <iostream> using std::cout; using std::endl; struct some_const_struct { const int arg1; const int arg2; }; class which_is_using_above_struct { public: some_const_struct* m_member; const some_const_struct* const m_const_member; public: const some_const_struct& get_member() const { return *m_member; } const some_const_struct& get_const_member() const { return *m_const_member; } void set_member(const int a, const int b) { if(m_member != NULL) { delete m_member; m_member = NULL; } m_member = new some_const_struct((some_const_struct){a, b}); } explicit which_is_using_above_struct(const int a, const int b) : m_const_member(new some_const_struct((const some_const_struct){a, b})) { m_member = NULL; } ~which_is_using_above_struct() { if(m_member != NULL) { delete m_member; } if(m_const_member != NULL) { delete m_const_member; } } }; int main() { which_is_using_above_struct c(1, 2); c.set_member(3, 4); cout << "m_member.arg1 = " << c.get_member().arg1 << endl; cout << "m_member.arg2 = " << c.get_member().arg2 << endl; cout << "m_const_member.arg1 = " << c.get_const_member().arg1 << endl; cout << "m_const_member.arg2 = " << c.get_const_member().arg2 << endl; return 0; } I'm just not quite sure if the statement: m_member = new some_const_struct((some_const_struct){a, b}); doesn't produce unnessesary use of some_const_struct's copy constructor, ergo allocating that struct twice. What do you think? And is it reasonable to make that struct's members const? (they're not supposed to change in their lifetime at all)

    Read the article

  • Why is const required [C++] ? [closed]

    - by Andy Leman
    Possible Duplicate: What's the difference between a const member function and a non-const member function? class Message { public: Message(const char* pStr, const char* key); Message(const char* pStr); Message(); void encryptMessage(); void decryptMessage(); const char* getUnMessage() const; const char* getEnMessage() const; void getMessage(); void getKey(); ~Message(); private: char* pUnMessage; char* pEnMessage; char* pKey; }; In this program, why using const? (2 different places) Please explain those 2 for me. Thank you very much!

    Read the article

  • "const char *" is incompatible with parameter of type "LPCWSTR" error

    - by N0xus
    I'm trying to incorporate some code from Programming an RTS Game With Direct3D into my game. Before anyone says it, I know the book is kinda old, but it's the particle effects system he creates that I'm trying to use. With his shader class, he intialise it thusly: void SHADER::Init(IDirect3DDevice9 *Dev, const char fName[], int typ) { m_pDevice = Dev; m_type = typ; if(m_pDevice == NULL)return; // Assemble and set the pixel or vertex shader HRESULT hRes; LPD3DXBUFFER Code = NULL; LPD3DXBUFFER ErrorMsgs = NULL; if(m_type == PIXEL_SHADER) hRes = D3DXCompileShaderFromFile(fName, NULL, NULL, "Main", "ps_2_0", D3DXSHADER_DEBUG, &Code, &ErrorMsgs, &m_pConstantTable); else hRes = D3DXCompileShaderFromFile(fName, NULL, NULL, "Main", "vs_2_0", D3DXSHADER_DEBUG, &Code, &ErrorMsgs, &m_pConstantTable); } How ever, this generates the following error: Error 1 error C2664: 'D3DXCompileShaderFromFileW' : cannot convert parameter 1 from 'const char []' to 'LPCWSTR' The compiler states the issue is with fName in the D3DXCompileShaderFromFile line. I know this has something to do with the character set, and my program was already running with a Unicode Character set on the go. I read that to solve the above problem, I need to switch to a multi-byte character set. But, if I do that, I get other errors in my code, like so: Error 2 error C2664: 'D3DXCreateEffectFromFileA' : cannot convert parameter 2 from 'const wchar_t *' to 'LPCSTR' With it being accredited to the following line of code: if(FAILED(D3DXCreateEffectFromFile(m_pD3DDevice9,effectFileName.c_str(),NULL,NULL,0,NULL,&m_pCurrentEffect,&pErrorBuffer))) This if is nested within another if statement checking my effectmap list. Though it is the FAILED word with the red line. Like wise I get the another error with the following line of code: wstring effectFileName = TEXT("Sky.fx"); With the error message being: Error 1 error C2440: 'initializing' : cannot convert from 'const char [7]' to 'std::basic_string<_Elem,_Traits,_Ax' If I change it back to a Uni code character set, I get the original (fewer) errors. Leaving as a multi-byte, I get more errors. Does anyone know of a way I can fix this issue?

    Read the article

  • const vs. readonly for a singleton

    - by GlenH7
    First off, I understand there are folk who oppose the use of singletons. I think it's an appropriate use in this case as it's constant state information, but I'm open to differing opinions / solutions. (See The singleton pattern and When should the singleton pattern not be used?) Second, for a broader audience: C++/CLI has a similar keyword to readonly with initonly, so this isn't strictly a C# type question. (Literal field versus constant variable in C++/CLI) Sidenote: A discussion of some of the nuances on using const or readonly. My Question: I have a singleton that anchors together some different data structures. Part of what I expose through that singleton are some lists and other objects, which represent the necessary keys or columns in order to connect the linked data structures. I doubt that anyone would try to change these objects through a different module, but I want to explicitly protect them from that risk. So I'm currently using a "readonly" modifier on those objects*. I'm using readonly instead of const with the lists as I read that using const will embed those items in the referencing assemblies and will therefore trigger a rebuild of those referencing assemblies if / when the list(s) is/are modified. This seems like a tighter coupling than I would want between the modules, but I wonder if I'm obsessing over a moot point. (This is question #2 below) The alternative I see to using "readonly" is to make the variables private and then wrap them with a public get. I'm struggling to see the advantage of this approach as it seems like wrapper code that doesn't provide much additional benefit. (This is question #1 below) It's highly unlikely that we'll change the contents or format of the lists - they're a compilation of things to avoid using magic strings all over the place. Unfortunately, not all the code has converted over to using this singleton's presentation of those strings. Likewise, I don't know that we'd change the containers / classes for the lists. So while I normally argue for the encapsulations advantages a get wrapper provides, I'm just not feeling it in this case. A representative sample of my singleton public sealed class mySingl { private static volatile mySingl sngl; private static object lockObject = new Object(); public readonly Dictionary<string, string> myDict = new Dictionary<string, string>() { {"I", "index"}, {"D", "display"}, }; public enum parms { ABC = 10, DEF = 20, FGH = 30 }; public readonly List<parms> specParms = new List<parms>() { parms.ABC, parms.FGH }; public static mySingl Instance { get { if(sngl == null) { lock(lockObject) { if(sngl == null) sngl = new mySingl(); } } return sngl; } } private mySingl() { doSomething(); } } Questions: Am I taking the most reasonable approach in this case? Should I be worrying about const vs. readonly? is there a better way of providing this information?

    Read the article

  • Immutable Method in Java

    - by Chris Okyen
    In Java, there is the final keyword in lieu of the const keyword in C and C++. In the latter languages there are mutable and immutable methods such as stated in the answer by Johannes Schaub - litb to the question How many and which are the uses of “const” in C++? Use const to tell others methods won't change the logical state of this object. struct SmartPtr { int getCopies() const { return mCopiesMade; } }ptr1; ... int var = ptr.getCopies(); // returns mCopiesMade and is specified that to not modify objects state. How is this performed in Java?

    Read the article

  • Immutable Method Java

    - by Chris Okyen
    In Java, there is the final keyword in lieu of the const keyword in c and c++. In the latter languages their is mutable and immutable methods such as stated in one answer by Johannes Schaub - litb the question how-many-and-which-are-the-uses-of-const-in-ce Use const to tell others methods won't change the logical state of this object. struct SmartPtr { int getCopies() const { return mCopiesMade; } }ptr1; ... int var = ptr.getCopies(); // returns mCopiesMade and is specified that to not modify objects state. How is this performed in Java?

    Read the article

  • How do I pass a const reference in C#?

    - by Maciek
    In C++, passing const references is a common practice - for instance : #include <iostream> using namespace std; class X { public : X() {m_x = 0; } X(const int & x) {m_x = x; } X(const X & other) { *this = other; } X & operator = (const X & other) { m_x = other.m_x; return *this; } void print() { cout << m_x << endl; } private : int m_x; }; void main() { X x1(5); X x2(4); X x3(x2); x2 = x1; x1.print(); x2.print(); x3.print(); } This very simple example illustrates how it's done - pretty much. However I've noticed that in C# this doesn't seem to be the case. Do I have to pass const references in C# ? what do I need the "ref" keyword for? Please note that I know and understand what C# reference and value types are.

    Read the article

  • IDL in ATL/COM: Can I publish a const of a complex type?

    - by Ptah- Opener of the Mouth
    I know how to publish a const of a simple type in IDL, for example: const long blah = 37 But I want to publish consts of complex types, with methods, or at least readable struct-like member fields. For example, perhaps a type called CarType, which has accessor fields like "get_Make", "get_Model", "get_Year", "get_BasePrice", et cetera. Then I would like to publish const instances, such as FORD_PINTO_1973. (Please don't read too much into the example, to tell me that this particular example would lend itself better to just regular classes without const instances or something like that). I have no idea how I would define, in IDL, the fact that FORD_PINTO_1973 has a Year field of 1973. Thanks in advance for any help.

    Read the article

  • How to initialize const float32x4x4_t (ARM NEON intrinsic, GCC) ?

    - by Eonil
    I can initialize float32x4_t like this: const float32x4x4_t = { 0.0f, 0.0f, 0.0f, 0.0f }; But this code makes an error Incompatible types in initializer: const float32x4x4_t = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, }; float32x4x4_t is 4x4 matrix built as: typedef struct float32x4x4_t { float32x4_t val[4]; } float32x4x4_t; How can I initialize this const struct?

    Read the article

  • C++ -- How can we call "delete this; " in a const-member function?

    - by q0987
    Hello all, I saw the code snippet as follows: class UPNumber { public: UPNumber(); UPNumber(int initValue); ... // pseudo-destructor (a const member function, because // even const objects may be destroyed) void destroy() const { delete this; } // why this line is correct??? ... private: ~UPNumber(); }; First, I am sure that above class definition is correct. Here is my question, why we can define the function 'destroy' as above? The reason being asking is that why we can modify 'this' in a const-member function? Thank you

    Read the article

  • Why does C# not allow const and static on the same line?

    - by Cuga
    Why does C# not allow const and static on the same line? In Java, you must declare a field as 'static' and 'final' to act as a constant. Why does C# not let you declare const's as final? I make the further distinction that in Java, every interface is public and abstract, whether this is explicitly declared or not. Aren't const's effectively static in nature? WHy does C# balk at this?

    Read the article

  • Can I use string concatenation to define a class CONST in PHP?

    - by selfsimilar
    I know that you can create global constants in terms of each other using string concatenation: define('FOO', 'foo'); define('BAR', FOO.'bar'); echo BAR; will print 'foobar'. However, I'm getting an error trying to do the same using class constants. class foobar { const foo = 'foo'; const foo2 = self::foo; const bar = self::foo.'bar'; } foo2 is defined without issue, but declaring const bar will error out Parse error: syntax error, unexpected '.', expecting ',' or ';' I've also tried using functions like sprintf() but it doesn't like the left paren any more than the string concatenator '.'. So is there any way to create class constants in terms of each other in anything more than a trivial set case like foo2?

    Read the article

  • Assigning a pointer variable to a const int in C++?

    - by John
    I'm wondering if anyone can explain the following to me: If I write int i = 0; float* pf = i; I get a compile error (gcc 4.2.1): error: invalid conversion from ‘int’ to ‘float*’ Makes sense - they are obviously two completely different types. But if instead I write const int i = 0; float* pf = i; It compiles without error. Why should the 'const' make a difference on the right hand side of the assignment? Isn't part of the idea of the 'const' keyword to be able to enforce type constraints for constant values? Any explanation I have been able to come up with feels kind of bogus. And none of my explanations also explain the fact that const int i = 1; float* pf = i; fails to compile. Can anyone offer an explanation?

    Read the article

  • Shoud a method that waits for a change of state be const?

    - by Space_C0wb0y
    In a multithreaded scenario, I have a method like this: bool WaitForChange( time_duration WaitTime ) const; This method waits either until the state of the object has changed and returns true, or until the timeout times out (how do you say that?) and returns false. My intuition is, that const is to protect against unwanted side-effects of the method itself, so this is fine. But then again, some user might think that the state of the could not have changed, since the method is declared const. Is that user stupid, or should I make the method non-const in order to avoid confusion?

    Read the article

  • C# coding standards” Use the const directive only on natural constants

    - by Nathan Wilfert
    I've seen these 2 guidelines in coding c# standard and I’m not sure the what the 2nd one means. With the exception of zero and one, never hard-code a numeric value; always declare a constant instead. Use the const directive only on natural constants such as the number of days of the week. 1st what is the definition of a natural constants and if the number is not a natural constants given the 1st rule how does one declare a constant in c# without the const directive? See http://www.scribd.com/doc/10731655/IDesign-C-Coding-Standard-232 for reference.

    Read the article

  • Function-Local Static Const variable Initialization semantics.

    - by Hassan Syed
    The questions are in bold, for those that cannot be bothered reading a question in depth. This is a followup to this question. It is to do with the initialization semantics of static variables in functions. Static variables should be initialized once, and their internal state might be altered later - as I (currently) do in the linked question. However, the code in question does not require the feature to change the state of the variable later. Let me clarrify my position, since I don't require the string object's internal state to change. The code is for a trait class for meta programming, and as such would would benifit from a const char * const ptr -- thus Ideally a local cost static const variable is needed. My educated guess is that in this case the string in question will be optimally placed in memory by the link-loader, and that the code is more secure and maps to the intended semantics. This leads to the semantics of such a variable "The C++ Programming language Third Edition -- Stroustrup" does not have anything (that I could find) to say about this matter. All that is said is that the variable is initialized once when the flow of control of the thread first reaches the code. This leads me to ponder if the following code would be sensible, and if not what are the intended semantics ?. #include <iostream> const char * const GetString(const char * x_in) { static const char * const x = x_in; return x; } int main() { const char * const temp = GetString("yahoo"); std::cout << temp << std::endl; const char * const temp2 = GetString("yahoo2"); std::cout << temp2 << std::endl; } The following compiles on GCC and prints "yahoo" twice. Which is what I want -- However it might not be standards compliant (which is why I post this question). It might be more elegant to have two functions, "SetString" and "String" where the latter forwards to the first. If it is standards compliant does someone know of a templates implementation in boost (or elsewhere) ?

    Read the article

  • noncopyable static const member class in template class

    - by Dukales
    I have a non-copyable (inherited from boost::noncopyable) class that I use as a custom namespace. Also, I have another class, that uses previous one, as shown here: #include <boost/utility.hpp> #include <cmath> template< typename F > struct custom_namespace : boost::noncopyable { F sqrt_of_half(F const & x) const { using std::sqrt; return sqrt(x / F(2.0L)); } // ... maybe others are not so dummy const/constexpr methods }; template< typename F > class custom_namespace_user { static ::custom_namespace< F > const custom_namespace_; public : F poisson() const { return custom_namespace_.sqrt_of_half(M_PI); } static F square_diagonal(F const & a) { return a * custom_namespace_.sqrt_of_half(1.0L); } }; template< typename F > ::custom_namespace< F > const custom_namespace_user< F >::custom_namespace_(); this code leads to the next error (even without instantiation): error: no 'const custom_namespace custom_namespace_user::custom_namespace_()' member function declared in class 'custom_namespace_user' The next way is not legitimate: template< typename F ::custom_namespace< F const custom_namespace_user< F ::custom_namespace_ = ::custom_namespace< F (); What should I do to declare this two classes (first as noncopyable static const member class of second)? Is this feaseble?

    Read the article

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