question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,419,461 | 3,419,514 | C++ Performance of structs used as a safe packaging of arrays | In C or C++, there is no checking of arrays for out of bounds. One way to work around this is to package it with a struct:
struct array_of_foo{
int length;
foo *arr; //array with variable length.
};
Then, it can be initialized:
array_of_foo *ar(int length){
array_of_foo *out = (array_of_foo*) malloc(sizeof(array... | I agree on the std::vector recommendation. Additionally you might try boost::array libraries, which include a complete (and tested) implementation of fixed sized array containers:
http://svn.boost.org/svn/boost/trunk/boost/array.hpp
|
3,419,463 | 3,445,109 | How do I release an InMemoryWorkspaceFactory in the ESRI Map Control? | I am embedding the ESRI Map Control into a custom ActiveX control written in MFC/C++. The custom ActiveX control serves as a Map Control wrapper so I can embed it into a specific environment that is runtime only and non-relational. Thanks to this site, I am able to load feature points into an in-memory workspace. Howev... | I discovered the answer to my question. It wasn't the in-memory workspace that needed to be closed, it was ArcObjects in general. The solution is to make sure to call the Shutdown method of the IAoInitialize interface during the WM_DESTROY message.
|
3,419,606 | 3,419,647 | Compress 21 Alphanumeric Characters in to 16 Bytes | I'm trying to take 21 bytes of data which uniquely identifies a trade and store it in a 16 byte char array. I'm having trouble coming up with the right algorithm for this.
The trade ID which I'm trying to compress consists of 2 fields:
18 alphanumeric characters
consisting of the ASCII characters
0x20 to 0x7E, Inclu... | If you have 18 characters in the range 0 - 127 and a number in the range 0 - 999 and compact this as much as possible then it will require 17 bytes.
>>> math.log(128**18 * 1000, 256)
16.995723035582763
You may be able to take advantage of the fact that some characters are most likely not used. In particular it is unli... |
3,419,767 | 3,576,005 | An efficient way to insert a single record using ADO | OK, this should be simple. I've just started using ADO in C++, and I'm trying to figure out the best way to insert a record.
At the moment I'm creating a new Recordset and opening it using Open(), but it seems strange to use ADODB::adCmdTable, because it's my understanding that it does a select *. Is there a better opt... | Apparently it doesn't do a select * ... at least the record count on the recordset is 0.
Instead of passing in a connection string, you can actually pass the connection object as an IDispatch*, which gets turned into a variant. So a better way of doing things is probably this (skipping the check of the HRESULT):
ADODB:... |
3,420,008 | 3,420,626 | Hex edit a dll to change a dependency name? | I have a dll which is dependent of OPENGL.DLL . However, Windows comes with OpenGL32.dll . I want to change this dependency name in the dll binary so it looks for OpenGL32.dll instead. I tried opening it in VS's binary editor but I cant seem to make the name longer. I can for instance change it to OpenDD.dll but I cant... | Its a bit hard to explain in english how to change the imported dll name in PE
(there're quite a few levels of indirection and RVAs), but
accidentally, I have a library that can be used for stuff like that.
PE32 only, though.
So here's the utility which you can use: http://nishi.dreamhosters.com/dllrepl_v0.rar
(with so... |
3,420,009 | 3,420,036 | avoid rounding error (floating specifically) c++ | http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/
I have been about this lately to review C++.
In general computing class professors tend not to cover these small things, although we knew what rounding errors meant.
Can someone please help me with how to avoid rounding error?
The tutorial shows a sample ... | The canonical advice for this topic is to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic", by David Goldberg.
|
3,420,103 | 3,420,141 | No copy constructor available or copy constructor is declared 'explicit' | Could somebody please explain why I'm getting a compile error here - error C2558: class 'std::auto_ptr<_Ty>' : no copy constructor available or copy constructor is declared 'explicit'
#include <memory>
#include <vector>
#include <string>
template<typename T>
struct test
{
typedef std::auto_ptr<T> dataptr;
typed... | Basically a std::auto_ptr cannot be used in this way.
others_.push_back( testptr( new test(other) ) );
Requires that a copy constructor that takes a const& exists and no such constructor exists for std::auto_ptr. This is widely viewed as a good thing since you should never use std::auto_ptr in a container! If you do... |
3,420,274 | 3,420,430 | Achieving Mutability When Mixing Primitives and Cocoa Collections | Okay, I think I might be over-complicating this issue but I truly am stuck. Basically, I am trying to model a weight set, specifically an olympic weight set. So I have the bar which is 45 lbs, then I have 2 weights of 2.5 lbs, 4 of 5 lbs, and then 2 of 10, 25, 35, and 45 respectively. This makes a total of 300 lbs.
bar... | Storing this in a dictionary isn't a natural fit. I think the best approach would be to make a Weight class that represents the weights, and stick them in an NSCountedSet. You can get the individual kinds of Weight and the counts for each kind, and you can get the weight of the whole set with [weightSet valueForKeyPath... |
3,420,297 | 3,420,334 | What's wrong with this copy constructor? | I've been trying to come up with a copy constructor for a tree. I've found quite a few suggestions.
This one interested me.
class TreeNode
{
int ascii;
TreeNode* left;
TreeNode* right;
public:
TreeNode() { ascii = 0; left = right = 0; }
TreeNode* clone();
// ...
};
TreeNode* TreeNode::clon... | Well, for starters it's not a copy constructor - the copy constructors have a very well defined syntax in C++, so a proper copy constructor would have the prototype TreeNode(TreeNode const &). Just to get the terminology right (and the compiler will still generate a copy constructor as it has no idea what the clone() f... |
3,420,312 | 3,420,529 | Efficiency of design patterns | Does anyone know any sites/books/articles covering best practices or theory around design patterns in high performance applications? It seems a lot of the patterns use indirection/abstraction/encapsulation in a way that may affect performance in computationally intensive code. Head First Design Patterns and even GoF me... | I’m surprised we aren’t asking what performance problems you are having!
In my experience, performance problems are usually tied to specific conditions and situations. Design patterns, on the other hand, are solutions to more general and abstract problems. It would seem a bit awkward to approach both in the same text: ... |
3,420,506 | 3,420,518 | How does one suppress specific warnings from source code on g++ 4.5 or later? | The first comment on a feature request for g++ says, "Starting with 4.5 you can disable a class of warnings in the source."
I looked through the 4.5.0 manual, but I can't find the syntax.
What is the syntax in g++ 4.5 and later to suppress individual warning classes in the source?
| http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html
http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas
|
3,420,657 | 4,040,276 | How to build facebook's scribe? | I just downloaded the source code of facebook's scribe. I'm new to it and having read the readme.build file , I can say I could barely understand how to build it. Could anyone give me the step by step procedures? thanks... :)
| All you need to do is follow the readme/build instructions that came with the package. If you don't have Linux installed in your PC, you can simply use a VM and install linux in it...
|
3,420,806 | 3,420,822 | Adding invariant check to every method of a Class | I have a class with many methods and would like to check for pre/post conditions, such as is mMember == null and invoke function x() if not.
Is it possible to add pre/post conditions to every member of that class automatically? The class is defined in class.h and all methods are defined in class.cpp. Being able to defi... | I have not ever been able to do this in C++; I've always used a set of macros manually added to each member function.
It sounds like a job that might be well-suited to Aspect Oriented Programming, though, and I see that there are libraries out there for AOP in C++, such as AspectC++. It might be worth at least taking ... |
3,420,948 | 3,421,900 | Static Analysis API's? | I am interested in static analysis tools that are out there. Or rather the API's that are supported to allow me to write my own tools using these API's.
I've written dozens over the years at my present employment that scrutinize our source code (C++) for various things. But one thing I want to know is if there are othe... | Our DMS Software Reengineering Toolkit is commercially available, general purpose machinery for parsing/analyzing/transforming source code for many languages, including C, C++, C#, Java, COBOL, ...
It uses explicit langauge definitions (e.g., BNF) to drive parsing machinery to build ASTs directly; DMS supports multiple... |
3,420,997 | 3,421,198 | C++ polymorphism - Auto detect derived type | I have certain code that I want to optimize. It looks like this:
function abc( string format ) {
if (format == "a") { // this is a string, I shouldn't have used single quote, sorry for the confusion
classx::a t;
doit(t);
}
if (format == "b"){
classx::b t;
doit(t);
}
if (format == "c"){
cla... | One possible approach that reduces the repetition to adding new entries to a function map:
template<class T> void innerAbc() {
T t;
doit(t);
}
typedef std::map<std::string, void (*)()> FuncMap;
FuncMap initHandlers() {
FuncMap m;
m["a"] = &innerAbc<classx::a>;
// ... extend here
return m;
} ... |
3,421,103 | 3,421,233 | Using undocumented classes in C++ | I'm in the process of reverse-engineering a Windows executable. I found a class that I want to use from some code that I inject into the executable (different thread, own stack). How would I go about declaring such a class, given method addresses and member variables structure?
For instance, let's say I found a class c... | If the class has no vtable, you could, in principle, create such a class in your own code, where all the function calls invoke the appropriate real implementations. You can do this by wring the member functions as naked functions containing an assembly jump instruction to the real implementation.
If the class has a vta... |
3,421,131 | 3,421,829 | Which backend languages should my compiler target? | I've written a compiler for a general-purpose programming language that produces an optimised parse tree of its input. This intermediate format is then run through a preprocessor to translate it into a target language for subsequent compilation to a native executable.
At present the only target language is C++, but I'd... | JavaScript, I'd add. Syntax like C, has lambdas, very popular, has very fast HQ implementations which compile to native code and is available everywhere. Double-plus: you can demo your compiler in any web browser and everybody is listening today, if you have something that cranks out JavaScript.
|
3,421,132 | 3,421,237 | Why to undefine macros before define them? | #undef GOOGLE_LONGLONG
#undef GOOGLE_ULONGLONG
#undef GOOGLE_LL_FORMAT
#ifdef _MSC_VER
#define GOOGLE_LONGLONG(x) x##I64
#define GOOGLE_ULONGLONG(x) x##UI64
#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...)
#else
#define GOOGLE_LONGLONG(x) x##LL
#define GOOGLE_ULONGLONG(x) x##ULL
#define GOOGLE_LL_FORMAT "... | Generally this is a bad idea. Ironically, given that you have "Google" in your symbol names, you might be curious to know that Google's C++ Style Guide urges against undefining macros before defining them. Basically, if you define a macro multiple times, you will get an error. The undef prevents these errors, which can... |
3,421,370 | 3,421,406 | Problem with strptime() - %p is not taken into account | I am trying to convert a date in a particular format using strptime, and i realized that the information about AM/PM is lost. Not sure why.
Here is the code.
struct tm t;
strptime("Wed 4/18/2007 4:28:22 PM", "%a %m/%d/%Y %H:%M:%S %p", &t);
std::cout<<t.tm_hour<<endl;
strptime("Wed 4/18/2007 4:28:22 AM", "%a %m/%d/%Y %H... | The problem here is with %H, which will read the hour in 24-hour format and ignore AM/PM. If you want to read the hour in 12-hour format and make use of AM/PM use %I in place of %H.
You can refer to the manual here.
|
3,421,540 | 3,421,589 | C type casting with "const" keyword | I usually use C type casting in C/C++ code. My question is, does adding the "const" keyword in the casting type mean anything to the result?
For example, I can think up several scenarios:
const my_struct *func1()
{
my_struct *my_ptr = new my_struct;
// modify member variables
return (const my_struct *)my_ptr... | Adding the const keyword in the casting type means that the result will be constant. The following will not compile in C++ (in C it has no effect):
int* x = (const int*)malloc(10); // cannot convert from 'const int *' to 'int *'
You really shouldn't use C type casting in your C++ code. It is not safe and should be use... |
3,421,786 | 3,422,558 | What is c++ equivalent of JNDI? | Is there anything equivalent to JNDI in C++?
I am not just looking ldap related libraries. I am interested to know the equivalent API's/Libraries available in C++. Common API for look-up, where implementation can handle against DNS, LDAP, Registry, FileSystem, DB.
| AFAIK the closest thing to JNDI in the C++ world is perhaps ADSI/Windows. While it provides a generic lookup interface that is mainly used to access directories of various kinds, i have seen it being used to look-up and read several other kinds of data sources. You would write an ADSI provider for DB, etc.
|
3,421,809 | 3,421,857 | How to calculate the MD5 of a char* using C++ |
Possible Duplicate:
In C++, How to get MD5 hash of a file?
I am currently using Ubuntu and am wishing to calculate the MD5 of a char*. was wondering if there is a pre-installed library that would just need including, or would I have to download a specially designed one?
| Include openssl/MD5.h and use the following to calculate the hash
MD5(<characters>, <length of it>, <the result(pointer)>);
|
3,421,817 | 3,421,834 | splitting int from a string | I have string with number on ints seperated by space delimiter. Can some one help me how to split the string into ints. I tried to use find and then substr. Is there a better way to do it ?
| Use a stringsteam:
#include <string>
#include <sstream>
int main() {
std::string s = "100 123 42";
std::istringstream is( s );
int n;
while( is >> n ) {
// do something with n
}
}
|
3,421,831 | 3,421,977 | What is the purpose of _GLOBAL__I_? | I have two functions declared as following, using extern "C" aming to avoid name mangling.
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jobject JNICALL Java_com_trident_tv_si_SIManagerImpl_nGetServiceDetails
(JNIEnv *, jobject, jint);
JNIEXPORT jobject JNICALL Java_com_trident_tv_si_SIManagerImpl_nGetServiceCur... | It looks to me like the two functions have the correct names ( the two preceded by T ), and that a third symbol (preceded by t) is created for gccs internal use.
They have been reordered though.
// SECOND FUNCTION, T = exported and in TEXT section
00004d58 T Java_com_trident_tv_si_SIManagerImpl_nGetServiceCurrentEvent
... |
3,421,847 | 3,490,813 | Detecting available graphics memory on the windows platform using C++ | I'd like to be able to detect how much graphics memory is available. I've written a C++ project that uses DirectShow.
Some ancient gfx cards can't do video properly and fall back to four colour mode. If I try to allocate more than one video window, the program just crashes on these machines without warning.
This is... | A really sneaky way that should work on XP and lower is to read the registry:
For example, I access \HKLM\Hardware\Devicemap\Video and get a GUID:
{3468769C-3D6B-4BB1-85B6-7B5AE7F4E8F8}
Then I access \HKLM\CCS\Control\Video, and read "HardwareInformation.MemorySize" for that device:
HKEY_LOCAL_MACHINE\SYSTEM\Contro... |
3,422,106 | 3,422,182 | How do I select a member variable with a type parameter? | I have a cache object that caches a number of different types of objects, as illustrated below:
class Cache
{
public:
ObjectTable<ObjTypeA> m_objACache;
ObjectTable<ObjTypeB> m_objBCache;
ObjectTable<ObjTypeC> m_objCCache;
};
The (horrible) way I'm currently using the cache at the moment is directly access... | Like this perhaps?
class Cache
{
// An "envelope" type which up-casts to the right ObjectTable<T>
// if we have a type parameter T.
struct ObjectTables : ObjectTable<ObjTypeA>,
ObjectTable<ObjTypeB>,
ObjectTable<ObjTypeC> {};
ObjectTables tables;
public:
tem... |
3,422,125 | 3,422,131 | Why copy constructor and assignment operator are disallowed? | #undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS
#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
I'm, reading open source code from google.
Why copy constructor and assignment operator are disallowed?
| To prevent instances of the class being copied or assigned. Most classes should not allow copying. Consider for example a BankAccount class - if you are writing software for a bank, they will not be too happy if you create copies of accounts and then apply credits and debits to those different copies.
|
3,422,272 | 3,425,357 | Input_iterator, find_if and modulus | I implemented an iterator, which has Fibonacci numbers as output. In my main() I'd like to find a number which is dividable by 17 (it's 34). Why doesn't work my find_if statement.
Thank you!
#include <boost/operators.hpp>
#include <algorithm>
#include <tr1/functional>
struct FibIter: boost::input_iterator_h... | Ok I solved it by using !boost::bind(...) instead of tr1::bind.
|
3,422,563 | 3,422,591 | cleaning up heavy use of template parameters | I have a set of classes in a logging framework used by project A and B. I am refactoring the framework so it can be used in project B and C. The refactoring mainly consists of giving everything template parameters: project A might run on an embedded device with poor/no STL implemenatation, while B and C just run on a p... | The “other” technique is very common in C++. The parameters class is usually called a “trait class”.
This is the way to go (why does it give you an uneasy feeling?). It is used pervasively in the Boost libraries and other C++ libraries. Even the standard library uses it, e.g. in the std::basic_string class.
An equally... |
3,422,625 | 3,422,643 | Accessing a local variable after "delete this" | I have a class that employs a reference counting mechanism. The objects of this class are eventually destroyed by calling delete this when the reference count drops to zero. My question is: can I use local on-stack variable after delete this? Here's a more specific example:
class RefCountedClass
{
public:
RefCounte... | Yes, you may do this, as long as the member variable itself is really only a reference to an external object.
(Please forgive the previous wrong answer, I was confused about the mutex_ variable.)
|
3,422,682 | 3,475,677 | Does boost have portable way to use ntohl/htonl/ntohs/htons type functions? | I am using UDP in particular boost::asio::ip::udp::socket sockets if that helps?
What is the header file?
What headers/classes do I need to handle network byte ordering with the UDP under boost?
| Just found it is enough to #include <boost/asio.hpp> as this pulls in all the platform dependent headers and gives access to htonl/ntohl which is exactly what I need.
Thanks all for the suggestions.
|
3,422,702 | 3,423,494 | QFile/QDataStream writing on existing data | I have got a file which is let's say 8 bytes length.
For example it looks like that:
22222222
Now, I read first let's say 5 bytes and changing them. For ex. to 11111
Finally, I want to write them ONTO EXCISTING DATA to the file, so I expect the file to look like that:
11111222
But I get only 11111, because file is eras... | Depending on what you are exactly doing with the file, you might want to memory map it:
QFile f("The file");
f.open(QIODevice::ReadWrite);
uchar *buffer = f.map(0, 5);
// The following line will edit (both read from and write to)
// the file without clearing it first:
for (int i=0; i<5; ++i) buffer[i] -= 1;
f.unmap(b... |
3,422,709 | 3,422,734 | Test for overflow in integer addition |
Possible Duplicate:
Best way to detect integer overflow in C/C++
i have tried to implement simple program which tests if overflow occurs during integer addition:
#include <climits>
#include <iostream>
#include <string>
using namespace std;
string overflow(long a,long b){
return ((a+b)>UINT_MAX)?"true":"false";... | Given unsigned int a, b, this expression can never evaluate to true:
(a+b) > UINT_MAX
The reason why it can't ever be true is because UINT_MAX is the max, so whatever result (a+b) is can never be greater than UINT_MAX, because that would be a contradiction.
You tried to use a bigger data type long to get around this, ... |
3,422,854 | 3,492,390 | C++ - How to call creator class/object | I need to call properties and functions of an object from a different class.
The idea is passing 'this' as a parameter to the other class constructor. E.g.:
instance = ClassName(this);
And then do:
ParentClass parentInstance;
ClassName::ClassName(MainApp _instance){
parentInstance = _instance;
}
However, my compi... | The problem is you have a circular reference - Game includes MainApp, and MainApp includes game. You need a 'forward declaration', as per the example by DeadMG.
See here.
|
3,422,911 | 3,429,716 | DirectX 9 C++ program crashes and wont re-open | I am just beginning to learn how to program DirectX 9 applications in C++, so I'm still not very good, and I'm messing it around quite a bit.
When I reopen the program after it crashes, the D3D Device fails to create with the result being D3DERR_INVALIDCALL. I am compiling with G++ in MinGW, using the DirectX August 20... | It seems something in the MsgProc was causing the window to fail for the device, and my program to crash. Thanks anyway.
|
3,423,276 | 3,423,282 | How to generate different random set of numbers, every time within the same program/function? | I understand, using srand(time(0)), helps in setting the random seed. However, the following code, stores the same set of numbers for two different lists.
Wondering, how do I generate the different set of numbers when the following function gets called more than once.
void storeRandomNos(std::list<int>& dataToStore)
{
... | do the srand(time(0)) once at the beginning of your program.
|
3,423,463 | 3,425,014 | block all connections connected to a boost signal | boost signals allows temporarily blocking a connection via a connection member function. However, I have a single signal with many connections. The connections are stored and maintained by their respective listeners. Now the broadcaster decides that it wants to stop sending signals for a while. There does not seem to b... | I don't know of any way to do that directly. If you are willing to permanently disconnect all slots, you can use the disconnect_all_slots() method. For example:
boost::signal<int ()> foo;
...
foo.disconnect_all_slots();
If you need to temporarily block them, the best workaround I can come up with is to use a custom ... |
3,423,474 | 3,588,441 | Global Hook in c++ doesn't work? | Trying to write a GLOBAL CBT HOOK,
this is My code, but my hooking app doesn't recieve any Messages, neither writes the dll something to a test file.
This is My Code:
#include "stdafx.h"
#include "GlobalHook.h"
#include "Stdafx.h"
#include <iostream>
#include <fstream>
#define DLL_EXPORT
#include "GlobalHook.h"
#... | The general structure seems sound.
#pragma comment(linker, "/section:ASEG,RWS") RWS might need to be rws
I'd strip down CBTProc so that you just log to file for the moment on every minmax, this would allow you to see that your dll has been injected properly.
WM_USER is ment to be used within a single app not across ap... |
3,423,578 | 3,423,621 | What is '\0' in C++? | I'm trying to translate a huge project from C++ to Delphi and I'm finalizing the translation. One of the things I left is the '\0' monster.
if (*asmcmd=='\0' || *asmcmd==';')
where asmcmd is char*.
I know that \0 marks the end of array type in C++, but I need to know it as a byte. Is it 0?
In other words, would the co... | '\0' equals 0. It's a relic from C, which doesn't have any string type at all and uses char arrays instead. The null character is used to mark the end of a string; not a very wise decision in retrospect - most other string implementations use a dedicated counter variable somewhere, which makes finding the end of a stri... |
3,423,788 | 3,423,841 | Simple way to set/unset an individual bit | Right now I'm using this to set/unset individual bits in a byte:
if (bit4Set)
nbyte |= (1 << 4);
else
nbyte &= ~(1 << 4);
But, can't you do that in a more simple/elegant way? Like setting or unsetting the bit in a single operation?
Note: I understand I can just write a function to do that, I'm just wondering if ... | Sure! It would be more obvious if you expanded the |= and &= in your code, but you can write:
nbyte = (nbyte & ~(1<<4)) | (bit4Set<<4);
Note that bit4Set must be zero or one —not any nonzero value— for this to work.
|
3,423,968 | 3,424,591 | compressed vector/array class with random data access | I would like to make "compressed array"/"compressed vector" class (details below), that allows random data access with more or less constant time.
"more or less constant time" means that although element access time isn't constant, it shouldn't keep increasing when I get closer to certain point of the array. I.e. conta... | I take it that you want an array whose elements are not stored vanilla, but compressed, to minimize memory usage.
Concerning compression, you have no exceptional insight about the structure of your data, so you're fine with some kind of standard entropy encoding. Ideally, would like like to run GZIP on your whole array... |
3,424,058 | 3,425,375 | How to pass complex objects ( std::string ) through boost::interprocess::message queue | Does anybody have some example code showing the pipeline of serializing a std::string sending it through a boost::interprocess::message_queue and getting it back out again?
| You need to serialize your data because boost::interprocess::message_queue operates on byte arrays. If all your messages are strings, just do:
size_t const max_msg_size = 0x100;
boost::interprocess::message_queue q(..., max_msg_size);
// sending
std::string s(...);
q.send(s.data(), s.size(), 0);
// receiving
std::str... |
3,424,335 | 3,424,359 | Solve for D given A,B,C and length of C-D, parallel to A-B | I'm trying to figure out how to do this. Essentially I have points A and B which I know the location of. I then have point C and point D which I only know the coordinates of C. I know the length of C-D and know that C-D must be parallel to A-B. How could I generally solve for D given A,B,C and length of C-D.
alt text h... | D = C ± (B-A) / |B-A| * |C-D|
If B=A there is no solution as the line AB degenerates to a point and parallelety of a line to a point is not defined.
Explanation
(B-A) / |B-A| is a direction vector of unit length. Multiplication by the length |C-D| results in the proper offset vector.
Edits: changed + to ± to provide bo... |
3,424,727 | 3,425,557 | can we pass arrays as arguments to functions by this syntax, under upcoming c++0x standards? | suppose we have following function:
void someFunction(int * araye){
for (int i=0;i<5;i++)
cout <<araye[i]<<' ';
cout <<'\n';
}
can we pass an array to this function by following syntax, under upcoming c++0x standards? :
someFunction({1,2,3,4,5});
if that's true, will we even be able to use this syntax in any case... | If your function takes const int*, rather than int*, then you just need a small trampoline function to pull the pointer out of the std::initializer_list<int> that the brace initialiser produces. Something like this (probably; I don't have a C++0x compiler to test with)
void someFunction(const int * array){
for (int... |
3,424,826 | 3,424,903 | Macro to both get (void*) address of item and length, for arrays and structs | I'm trying to design a macro to produce several related data structures related to things that need initialization. The code has to compile under both C and C++. The goal is to have something like:
MUNGE_THING(struct1);
MUNGE_THING(array1);
turn into something equivalent to
munge_thing((void*)&struct1, sizeo... | I'm not sure what problem you are having with &array1. This C++ worked exactly as expected (all values the same)
int main(int argc, char* argv[])
{
int array1[10];
printf("%x %x\n", array1, &array1);
cout << array1 << " " << &array1 << endl;
void* ptr1 = array1;
void* ptr2 = &array1;
printf(... |
3,424,957 | 3,425,043 | Why doesn't wstring::c_str cause a memory leak if not properly deleted | Code Segment 1:
wchar_t *aString()
{
wchar_t *str = new wchar[5];
wcscpy(str, "asdf\0");
return str;
}
wchar_t *value1 = aString();
Code Segment 2
wstring wstr = L"a value";
wchar_t *value = wstr.c_str();
If value from code segment 2 is not deleted then an memory leak does not occur. However, if value... | An important rule: you must use delete on anything that was created by new, and you mustn't delete anything else.
wstr.c_str() returns a pointer to a buffer that's managed by the wstring object. It will be deallocated when the string is destroyed, after which the pointer will no longer be valid. Using delete on this is... |
3,425,000 | 3,425,027 | Nested struct type in a template class | template <typename vec1, typename vec2>
class fakevector
{
public:
/* Do something */
};
template <class A>
class caller
{
public:
struct typeList
{
struct typeOne
{
//...
};
};
typedef fakevector<typeList::typeOne,int> __methodList; /* This will ... | Try:
typedef fakevector<typename typeList::typeOne,int> __methodList;
http://www.comeaucomputing.com/techtalk/templates/#typename
|
3,425,084 | 3,425,141 | Storing elements in the list, in the ascending order | Goal is, I've multiple lists of elements available, and I want to be able to store all of these elements into a resultant list in an ordered way.
Some of the ideas that comes to my mind are
a) Keep the result as a set (std::set), but the B-tree , needs to rebalanced every now and then.
b) Store all the elements in a li... | At a glance, your code looks like it's doing a linear search of the list in order to find the place to insert the item. While it's true that std::set will have to balance its tree (I think it's a Red-Black Tree) in order to maintain efficiency, chances are it'll do so much more efficiently than what you're proposing.
|
3,425,494 | 3,425,504 | how to run a batch file using c++? | how to run a batch file using c++?
I dont know any thing about that
| Please see the system() function.
http://www.cplusplus.com/reference/clibrary/cstdlib/system/
|
3,425,517 | 3,425,544 | varargs function crashing | I have a function that is supposed to take a variable number of arguments (using varargs) based on a format string:
void va(const char* name, const char* argformat, ...) {
int numOfArgs = strlen(argformat);
std::string buf = "asdf";
va_list listPointer;
va_start(listPointer, numOfArgs);
char* blah... | It should be va_start(listPointer, argformat). va_start takes the last named parameter as its second argument. (Which technically means that you don't need to pre-calculate the length of the argument string at all — just iterate over the characters (iterating over the varargs as you go) until you get to the end of the ... |
3,425,633 | 3,595,878 | How to detect points which are drastically different than their neighbours | I'm doing some image processing, and am trying to keep track of points similar to those circled below, a very dark spot of a couple of pixels diameter, with all neighbouring pixels being bright. I'm sure there are algorithms and methods which are designed for this, but I just don't know what they are. I don't think edg... | Personally I like this corner detection algorithms manual.
Also you can workout naive corner detection algorithm by exploiting idea that isolated pixel is such pixel through which intensity changes drastically in every direction. It is just a starting idea to begin from and move on further to better algorithms.
|
3,426,035 | 3,426,055 | Proper handling of GetLastError (and others) in a multithreaded context | Is it correct to assume that GetLastError (and variants) are per-thread or is it per-process? The problems if it is per-process are somewhat obvious in multithreaded apps because there is no way to guarentee that no other Win32 calls were made between your failed call and GetLastError. Sometimes the value of GetLastE... | the docs are absolutely unambiguous about this:
GetLastError Function
Retrieves the calling thread's
last-error code value. The last-error
code is maintained on a per-thread
basis. Multiple threads do not
overwrite each other's last-error
code.
So they said it three times (in a single paragraph!): should be... |
3,426,067 | 3,427,617 | How to mock templated methods using Google Mock? | I am trying to mock a templated method.
Here is the class containing the method to mock :
class myClass
{
public:
virtual ~myClass() {}
template<typename T>
void myMethod(T param);
}
How can I mock the method myMethod using Google Mock?
| In previous version of Google Mock you can only mock virtual functions, see the documentation in the project's page.
More recent versions allowed to mock non-virtual methods, using what they call hi-perf dependency injection.
As user @congusbongus states in the comment below this answer:
Google Mock relies on adding m... |
3,426,101 | 3,453,209 | static char * vs #define in C++ VS2005 | I have a large program with several large DLL's that are compiled with MFC and /clr. There is a limit of 65535 global FieldRVA entries in an assembly. If it is more the loader raises an exception. I already have Enable String Pooling (/GF).
I have alot of code like:
static char *pSTRING_ONE = "STRING_ONE";
if I compil... | Unfortunately, the best solution to our problem was to include the offending code within a class.
// Old Way
static char *pSTRING_ONE = "STRING_ONE";
New
class CFieldDefs
{
public:
static char *pSTRING_ONE;
}
char *CFieldDefs::pSTRING_ONE = "STRING_ONE";
Usage:
CFieldDefs:pSTRING_ONE;
Even though the change ... |
3,426,165 | 3,426,234 | Is using double faster than float? | Double values store higher precision and are double the size of a float, but are Intel CPUs optimized for floats?
That is, are double operations just as fast or faster than float operations for +, -, *, and /?
Does the answer change for 64-bit architectures?
| There isn't a single "intel CPU", especially in terms of what operations are optimized with respect to others!, but most of them, at CPU level (specifically within the FPU), are such that the answer to your question:
are double operations just as fast or
faster than float operations for +, -,
*, and /?
is "yes" -- wi... |
3,426,225 | 3,426,289 | Do classes with uninitialized pointers have undefined behavior? | class someClass
{
public:
int* ptr2Int;
};
Is this a valid class (yes it compiles)? Provided one assigns a value to ptr2Int before dereferencing it, is the class guaranteed to work as one would expect?
| An uninitialized pointer inside a class is in no way different from a standalone uninitailized pointer. As long as you are not using the pointer in any dangerous way, you are fine.
Keep in mind though that "dangerous ways" of using an uninitialized pointer include a mere attempt to read its value (no dereference necess... |
3,426,351 | 3,426,367 | Why does WinAPI's GetSystemInfo tell that my quad-core machine has 8 cores? | I'm trying to find out how to get the number of CPU cores programmatically. This is the code I'm using:
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );
std::cout << "CPU count: " << sysinfo.dwNumberOfProcessors << std::endl;
This is running on Windows on the iMac i7 via Boot Camp. It would be nice to find out that App... | If your machine is hyper-threaded, it will have 8 virtual cores.
Check the Performance tab of the Windows Task Manager, see how many CPUs are displayed.
|
3,426,355 | 3,426,415 | Is atomic CAS required when setting a boolean to true | I have class where a bool is access concurrently. However in my case it is only initialized to false once in the constructor, and after that it set to false. Am i correct to believe that even though a race might occur the result will be valid and defined? Since the entire bool doesn't have to be written to inorder for... | I'm not quite sure of the question, but you should probably look into the "volatile" keyword. IIRC, it insures the value is updated whenever accessed.
http://en.wikipedia.org/wiki/Volatile_variable
HTH
|
3,426,681 | 3,426,711 | instant messaging program - works with 127.0.0.1, but not with other computers | I have followed a tutorial on http://www.codeproject.com/KB/IP/beginningtcp_cpp.aspxt
which teaches how to use winsockets with c++, i finally managed to get my program to work, by testing wiht 127.0.0.1, i can open two process instances of my program and then make one listen on port (700) and then connect to it with th... | Is either one of you behind a NAT firewall/router? The IP address you present to the outside world might not be the one that your own computer uses, which would make it impossible for the program to communicate with you unless you had some sort of tunnel set up through the NAT.
|
3,426,742 | 3,426,812 | Getting return value of a function called with assembly | I am using Microsoft Visual C++ 2010.
If I have a function like this:
const char* blah(void);
and I want to call it like this:
__asm {
call blah;
...
}
How do I get the return value of the function in the assembly?
| The return value is in the EAX register.
|
3,426,756 | 3,427,531 | How to make tab text orientation of a notebook vertical (in gtkmm) | I want my notebook tab labels to be rotated by 90°.
I tried the set_angle() function of Gtk::Label but it doesn't work:
#include <gtkmm.h>
int main(int argc, char *argv[])
{
Gtk::Main kit(argc, argv);
Gtk::Window mainwindow;
Gtk::Notebook sidebar;
Gtk::Label tab;
mainwindow.add(sidebar);
sid... | It seems you are adding the label as the child widget. You don't have a widget to be the page child in your code, but if you did and named it "child", you'd have something like this:
sidebar.set_tab_pos(Gtk::POS_LEFT);
tab.set_angle(90);
tab.set_text("text");
sidebar.append_page(child, tab);
|
3,427,047 | 3,428,024 | Should the NVI idiom be used for simple interface classes? | Which should I use?
struct IFilterTreeNode
{
virtual unsigned int GetEasiestProveRank() const = 0;
virtual unsigned int GetEasiestDisproveRank() const = 0;
virtual unsigned int GetEasiestProveNumber() const = 0;
virtual unsigned int GetEasiestDisproveNumber() const = 0;
virtual std::vector<IFilterTr... | I'm lazy, and most of our codebase uses the first choice, so that's the one I'd go with. I'd switch to the second choice immediately when things start getting more complex. But like I said, I'm lazy. :-)
The second choice is definitely more future-proof and more flexible. Good programmers make classes easy to use. ... |
3,427,309 | 3,427,805 | Bug in best-fit ellipse code | I would appreciate an extra set of eyes on this code. It's supposed to find a best-fit ellipse for a set of data points. The problem is that the length of major & minor axis (aDist and bDist) are coming out larger than they should.
Inputs:
points - a set of (x,y) coordinates for the data points; x and y are non-neg... | You need to divide mat by the total number of points to get the correct covariance matrix.
|
3,427,416 | 3,427,498 | Iterator member behavior | I was expecting the second assert in the following to pass. I'm asking for your help.
Edit: It didn't work when I had poss everywhere instead of poss_a in some places.
#include <vector>
#include <cassert>
class Sampler
{
public:
std::vector<int*> poss;
std::vector<int*>::const_iterator poss_it;
Sampler(std::vector... | The poss_it(poss.begin()) line in your initializer list is pulling an iterator from the poss that is the input to the constructor, not the one that is a field of the class.
This is a scope issue. When you're in the constructor, it's fine, because your iterator is a pointer to the input to the function. When you leave t... |
3,427,483 | 3,427,716 | Why is a QProgressDialog doesn't get updated after executing a QProcess? | I am using a QProgressDialog to show the status of a long running operation, which includes a step of running an external executable. I run the external executable using the QProcess::execute() method. QprogressDialog works fine updating the label text till it reaches the QProcess::execute() method, after which it does... | QProcess::execute() is a blocking method: it will block its calling thread until the spawned process will terminate. It you call this method from the main thread, UI events will not be handled until the method will return.
To get around this you can create an instance of QProcess (rather than using its static methods) ... |
3,427,750 | 3,427,790 | Difference between Array initializations | Please see the following statements:
char a[5]="jgkl"; // let's call this Statement A
char *b="jhdfjnfnsfnnkjdf"; // let's call this Statement B , and yes i know this is not an Array
char c[5]={'j','g','k','l','\0'}; // let's call this Statement C
Now, is there any difference between Statements A and C?
I mean both sh... | If a[] is static then so is c[] - the two are equivalent, and neither is a string literal. The two could equally well be declared so that they were on the stack - it depends where and how they are declared, not the syntax used to specify their contents.
|
3,427,792 | 3,427,847 | Troubles with errno.h | I'm coding a simple SDL program with VC10. The problem that I am having is at compiling the program:
Error 1 error C1083: Cannot open include file: 'errno.h': No such file
or directory c:\program files\microsoft visual studio
10.0\vc\include\cerrno 14
Error 2 error C1083: Cannot open include file: 'errno.h': No su... | Seems like a bad installation, the file errno.h is missing. It should be somewhere in compiler includes and you need it because cerrno refers to it.
|
3,428,072 | 3,428,173 | How to force Windows Mobile device to use GPRS for internet connection | I'm on WiFi and EDGE/GPRS too. I'm using WiFi for debugging in Visual Studio 2008 but I want my app use EDGE/GPRS for internet connection (socket creation) not WiFi
thx & bye,
Attila
| I found the solution:
I deploy my app on device, I turn off wifi, I start my app, It uses GPRS, finally I turn on wifi and attach debugger to my device
|
3,428,177 | 3,428,718 | Boost crash when linking Visual Studio 2008 Express '/Mtd' setting | TLDR
Linking my fresh boost build with Visual Studio (/Mtd) causes boost to throw a 'bad_alloc' exception before entering the main function.
Details
I built the boost library using the instructions from the Getting Started instructions. After setting up the prerequisites I used the following build command:
bjam -j8 --b... | My solution workaround goes as follows:
Install boost using the BoostPro Installer. It installs Boost in the 'C:\Program Files' directory.
Use the (included) bcp utility to create a slimmed down copy of the boost repository. See my original post for an example.
Add the generated headers to my project folder
Also copy ... |
3,428,258 | 3,428,282 | Should I be doing anything to help manage linker namespace pollution WRT internal-use classes? | In a complex library or framework, there are obviously times when classes are needed purely internally, to implement higher level functionality.
Often these internals are tightly coupled to how the internals work, so there is no point in making them available to users - all they could do with them is to try to tamper w... | I usually put such identifiers into a details namespace:
namespace some_component {
namespace details {
class helper { ... };
}
}
some_component::details::helper is obviously an implementation detail.
|
3,428,361 | 3,428,542 | zlib compiling on windows 7 (x64) | I had compiled zlib on my comp to compile libxml (for collada dom).
But I don't know which directories are supposed to be /lib and /include at compiling libxml.
Sorry for my English and my noobinity :) Thx for the answers and the worthy time You have spent on answering me.
| Whichever folder the zlib header files are in is the folder to add into the list of include paths when compiling libxml. Similarly the folder that holds your compiled zlib library should go into the linker's list of search directories. Is that what you mean?
|
3,428,422 | 3,477,564 | how to set system ip programmatically | C++
how to programmatically change system IP...
and if the the account has Limited Rights how to use the password to perform the task
| Take a look at this link on msdn. I believe the function you should look into is:
DWORD AddIPAddress(
__in IPAddr Address,
__in IPMask IpMask,
__in DWORD IfIndex,
__out PULONG NTEContext,
__out PULONG NTEInstance
);
|
3,428,545 | 3,428,601 | Possible to include C/C++ header files in a .pro file? | Is it possible to include C/C++ header files in a qmake (.pro) file?
I have a version.h header file with several definitions for my project (strings, version numbers, etc.). I also have an .rc file for Windows to add version info to my exe/dll, which includes this header file.
So, can I somehow get the #defines in my h... | You can use the DEFINES variable in the .pro file. The following works with gcc and clang.
# A definition without a value
DEFINES += USE_X86_ASM
# A definition with a value
DEFINES += SOME_DEFINITION=value
# A more complicated value needs quoting
DEFINES += COMPANY_NAME=\"Weird Apps LLC.\"
# Defining a string can be... |
3,428,570 | 3,428,586 | Adding an in-proc COM Server object to a C# application | I am new to COM and need to add a Server COM object to my c# application so I can call its methods and implement events. The documentation I have says this requires a COM-aware language such as Visual C++. My app is written in C# so I'm not sure how this is going to work. Any direction would be appreciated.
I am wri... | You can add the COM object as a reference. .NET will create an interop assembly to work with the COM object, just like it was a .NET type.
|
3,428,750 | 3,428,777 | Memory leak with std::string when using std::list<std::string> | I'm working with std::list<std::string> in my current project. But there is a memory leak somewhere connected with this. So I've tested the problematic code separately:
#include <iostream>
#include <string>
#include <list>
class Line {
public:
Line();
~Line();
std::string* mString;
};
Line::Line() {
m... | In the first case, the list class has no idea you allocated the string with new, and cannot delete it. In particular, the list only ever contains a copy of the string that you passed in.
Similarly, in the second case, you never free the line object s, and thus you leak memory. The reason why the internal string is dele... |
3,428,894 | 3,428,905 | Number of permissible active iterators into a vector | For example is the following valid?
std::vector<int> vec(5, 0);
std::vector<int>::const_iterator it1(vec.begin());
std::vector<int>::const_iterator it2(vec.begin());
//Use it1 and it2 like they don't know about each other.
Is there a special name for a container that permits multiple active iterators?
| Yes, it's valid.
You can have as many iterators into a vector as your system has memory to hold iterators.
The special name for this type of container is "any STL container". All containers allow this.
Maybe explain why you think this shouldn't be allowed?
|
3,428,903 | 3,428,925 | += on a vector without boost | Is there any way to use the += operator with a vector without using boost or using a derivated class?
Eg.
somevector += 1, 2, 3, 4, 5, 6, 7;
would actually be
somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(3);
etc.
| With a little ugly operator overloading, this isn't too difficult to accomplish. This solution could easily be made more generic, but it should serve as an adequate example.
#include <vector>
Your desired syntax uses two operators: the += operator and the , operator. First, we need to create a wrapper class that al... |
3,428,907 | 3,428,959 | How does boost::ptr_vector deep copy the underlying objects? | ptr_vector is copy constructible and copy assignable. How can it deep copy the underlying objects when it doesn't know their concrete types?
| The boost::ptr_vector container has an optional template parameter, CloneAllocator, that defines the cloning policy. The default allocator is the heap_clone_allocator, which simply invokes the copy constructor to clone an object.
The Clone Allocator is used as a way to add a layer of indirection around the cloning. F... |
3,428,956 | 3,428,972 | Deleting an object in C++ | Here is a sample code that I have:
void test()
{
Object1 *obj = new Object1();
.
.
.
delete obj;
}
I run it in Visual Studio, and it crashes at the line with 'delete obj;'.
Isn't this the normal way to free the memory associated with an object?
I realized that it automatically invokes the destructor... ... |
Isn't this the normal way to free the memory associated with an object?
This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it,... |
3,429,199 | 3,429,280 | Finding security problems in a given code | Can some one please tell me an approach for finding security flaws in a given code. For ex: in a given socket program. Any good examples or good book recommendations are welcome.
Thanks & Regards,
Mousey
| The lowest hanging fruit in this category would be to simply search the source for functions which are commonly misused or are difficult use safely such as:
strcpy
strcat
sprintf
gets
then start looking at ones that are not inherintly too bad, but could be misused. Particularly anything that writes to a buffer can po... |
3,429,387 | 3,429,410 | Using c++ template an argument to an objective-c method | How can I use a c++ template as an a parameter to an objective-c method?
essentially I want to do something like this:
template<typename T>
- (void)method:(T)arg
but that doesn't work. according to this document this is possible however it does not provide any examples. Does anyone know how tot do this?
| No you can't do that.
Objective-C classes, protocols, and categories cannot be declared inside a C++ template, nor can a C++ template be declared inside the scope of an Objective-C interface, protocol, or category.
Even if it is possible to declare that template, it is useless as Objective-C methods cannot be overloa... |
3,429,412 | 3,429,418 | question about % operator in C++ | i have following code
#include <iostream>
#include<exception>
#include <cstdlib>
int main(){
for (int i=0;i<100;i++){
std::cout<<i<<" ";
if (i %5==0){
abort();
}
}
return 0;
}
but it only writes 0 and says that abort was called why?i think it should ouput
0 ... | Think of % as "remainder after division." 0 / 5 equals 0 with a remainder of 0.
|
3,429,670 | 3,429,930 | How to initialize with multiple return values in c++(0x) | tuple in boost and TR1/c++0x provides a convenient (for the writer of the function) method to return two values from a function--however it seems to damage one major feature of the language for the caller: the ability to simply use the function to initialize a variable:
T happy();
const auto meaningful_name(happy()); /... | std::tuple<Type1, Type2> returnValue = sad();
Type1& first = std::get<0>(returnValue);
Type2& second = std::get<1>(returnValue);
I'm not sure what your fourth bullet means, but that satisfies all the rest.
*edit: Based on your comment above, I figured out what you meant by the fourth bullet.
struct Object {
Object... |
3,430,060 | 3,430,065 | Why can't I compile this non-CLR program in VC++ 2008? How to do it? | Why can't I compile/run this non-CLR program in VC++ 2008?
How to do it?
MyProgram.cpp
#include <iostream>
namespace System
{
public class Console
{
public:
static void WriteLine(char str[])
{
std::cout<<str;
}
};
}
int main()
{
System::Console::WriteLine("... | That isn't a non-CLR C++ program. In proper C++, classes cannot be public (or private). You want:
namespace System
{
class Console
{
public:
static void WriteLine(char str[])
{
std::cout<<str;
}
};
}
Also in C++ character literals are const, so your function should b... |
3,430,419 | 3,430,437 | char printable program | i have program which prints all char from char_min to char_max here is code
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
char c;
c=CHAR_MIN;
while(c!=CHAR_MAX){
printf("d\n",c);
c=c+1;
}
return 0;
}
but it prints only all d why?ouput is like th... | printf("d\n",c); /// Means just print "d" (c is ignored)
printf("%d\n",c); /// Means print the decimal value of varaible c
printf("%c\n",c); /// Means print the charcter value of varaible c
Using "%d" will just print "0", "1", "2" etc.
Using "%c" will print the character values: "A", "B", "C" etc. Note, h... |
3,430,462 | 3,430,476 | delete function in C++ | I saw an example of using the function: delete in cpp and I didn't completely understand it.
the code is:
class Name {
const char* s;
//...
};
class Table {
Name* p;
size_t sz;
public:
Table(size_t s = 15){p = new Name[sz = s]; }
~Table { delete[] p; }
};
What is the exact action of th... | delete isn't a function, it's an operator.
A delete expression using [] destroys objects created with new ... [] and releases the associated memory. delete[] must be used for pointers returned by new ... []; non-array delete only on pointers returned by non-array new. Using the non-matching delete form is always incorr... |
3,430,762 | 3,430,776 | a compiler generated default constructor in c++ | declaring a struct Table:
struct Tables {
int i;
int vi[10];
Table t1;
Table vt[10];
};
Tables tt;
assuming that a user-deault contructor is defined for Table.
here tt.t1 will be initialized using the default contructor for Table, as well as each element in tt.vt.
On the other hand tt.i an... | No, no error will be thrown. You will have a mild case of undefined behaviour. However, as integers don't have trap values, there is no way the behaviour can be detected.
Note that the C++ language itself throws exceptions only very, very rarely - about the only times I can think of where it does it is when performing... |
3,430,823 | 3,430,860 | requirement for a function to be inline in c++ | what are the requirement for a function so it could be executed inline in c++?
is there a case that a function can't be inline?
or any function can be inline and it is the responsibility of the programmer to decide how to define the function, based on run time and compilation-time considerations?
|
what are the requirement for a
function so it could be executed
inline in c++?
It needs to be defined at every spot in which it's called (typically this is done by putting it in a .h).
is there a case that a function can't
be inline?
Not in terms of the language standard, I believe, although of course each co... |
3,430,848 | 3,430,868 | what will be the addressing mode in assembly code generated by the compiler here? | Suppose we've got two integer and character variables:
int adad=12345;
char character;
Assuming we're discussing a platform in which, length of an integer variable is longer than or equal to three bytes, I want to access third byte of this integer and put it in the character variable, with that said I'd write it like ... | The best thing to do in situations like this is to try it. Here's an example program:
int main(int argc, char **argv)
{
int adad=12345;
volatile char character;
character=*((char *)(&adad)+2);
return 0;
}
I added the volatile to avoid the assignment line being completely optimized away. Now, here's what th... |
3,430,942 | 3,431,011 | C++: Question about copy constructors | I have a class where I use this to initialize a void* pointer. But the problem is, when I pass an instance of that class by value, the pointer will not change to the new address on the stack. So, I thought to override the copy constructor to reassign the pointer with the new address of this. But I need variables to cal... | Not sure if this helps, but you can actually call the superclass copy constructor in your copy constructor:
GetsCopiedByValue(GetsCopiedByValue const& other) :
SuperClass(other), var1(other.var1)
{
t1->set_GetsCopiedByValue_Address(this);
}
But I think that even if you omit this base-class constructor call, ... |
3,430,981 | 3,430,991 | Returning reference from a function and modifying it | #include<iostream>
int& f(){
static int x = 0;
x++;
return x;
}
int main(){
f() += 1; //A
f() = f() + 1; //B
std::cout << f();
}
The above code outputs 6 on gcc and 5 on MSVC. Now when I modify A and B to f()=f() I get 5 on both compilers. What is the big deal here? Is the behavior undefined. If yes , why?
| It is undefined, because in this code:
f() = f() + 1;
it is not defined which call to f() happens first.
|
3,431,008 | 3,431,032 | C++/CLI or plain C++ with regards to graphics / rendering | I come from a .NET background and will be going into the field of rendering / graphics using OpenGL/DirectX. For this purpose C++ will be my language of choice to interact with these rendering frameworks.
As I understand it Visual C++ allows native support for CLI which is an extension to C++ that allows the applicatio... | It really depends on what you're looking for. C++/CLI has advantages that few of the other .NET languages share (strong support for mixed mode being one of them), but it's still a .NET paradigm at heart. The only reason you're going to delve into it is if you want what .NET offers. If your primary need is for full-s... |
3,431,023 | 3,431,122 | LINK : fatal error LNK1104: cannot open file 'libcollada14dom21.lib' | I have hit this error at the linker stage:
LINK : fatal error LNK1104: cannot
open file 'libcollada14dom21.lib'
I dunno why, libcollada14dom21.lib is in VSDIR/VC/lib.
| Make sure that you add libcollada14dom21.lib to Project Options -> Linker -> Input -> Additional Dependencies.
|
3,431,057 | 3,431,082 | Linking in several C object files that contain functions with equivalent signature | Lets say I have a C++ program and I want to call functions from a C object file in it. The constraint is that I'm not allowed to make any changes to the C source files.
In this case I would include the C header as extern "C" in my C++ file, call the function, compile the C object using gcc -c, and pass the result to g+... | Your last paragraph has a good solution - why not make a C++ file something like this:
namespace c_namespace_1 {
#include "CFile1.c"
}
namespace c_namespace_2 {
#include "CFile2.c"
}
And so on.... then you could compile this file as C++ and not have to modify the original sources.
|
3,431,371 | 3,431,497 | How does initialization to a value compare in performance to assignment? | I read that for user-defined types, postponing the defintion of a variable until a suitable initializer is available can lead to better performance.
why?
| For user-defined types in particular, the constructor and setting method could me arbitrarily complex and time-consuming. Taking Steven's example:
X x; // Calls X()
x.Set(42);
X x(42); // Calls X(int)
... the implementation of X::X() and X::Set() might both be very time-consuming, and that's why you read that the... |
3,431,434 | 3,511,233 | Video Stabilization with OpenCV | I have a video feed which is taken with a moving camera and contains moving objects. I would like to stabilize the video, so that all stationary objects will remain stationary in the video feed. How can I do this with OpenCV?
i.e. For example, if I have two images prev_frame and next_frame, how do I transform next_fram... | I can suggest one of the following solutions:
Using local high level features: OpenCV includes SURF, so: for each frame, extract SURF features. Then build feature Kd-Tree (also in OpenCV), then match each two consecutive frames to find pairs of corresponding features. Feed those pairs into cvFindHomography to compute ... |
3,431,461 | 3,431,491 | Debug Assertion Error - delete call on char pointer | So I decided to dwelve a bit within the pesty C++.
When I call the delete function on a pointer to a simple class that I created I'm greeted by a Debug Assertion Failure -Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse). I assume this is because I've handled the string manipulation wrong and thus causing memory corru... |
So I decided to dwelve a bit within the pesty C++.
Then do yourself a favor and use C++ right. That would be to use std::string:
// name
std::string name_;
animal::animal(const std::string& name)
: name_(name)
{
}
//animal::~animal() // not needed any longer
//note: copying also automatically taken care of by s... |
3,431,469 | 3,431,482 | C++ begin and end of function macros | I'm trying to write two simple macros for begin and end of functions in order to manage and log all the Exceptions in my program. In other words, I wanna have a try-catch block in all of my functions.
in simple case consider the following macros.
#define __BEGIN_FUNCTION__ try {
#define __END_FUNCTION__ } catch(std::ex... | That's a horrible way to handle exceptions. If an exception is thrown, it is because an error occurred. You then have to either handle the error, solving the problem that occurred, or allow it to terminate the program.
Ignoring the exception makes no sense.
At the very least, you should rethrow the exception once it's ... |
3,431,701 | 3,431,720 | What's wrong with my memcpy? | I have written a function to implement memcpy
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
char *memcpy(char *dest,char *src,int n){
char *ch=dest;
while (n--)
*ch++=*src++;
return dest;
}
int main(){
char *src="georgia";
int n=strlen(src);
char *des... | Because you're printing a single character.
std::cout<<*memcpy(dest,src,n)<<std::endl;
This dereferences the destination buffer (*memcpy) and therefore returns the first character of the string (which is g). You should be fine using this:
std::cout << memcpy(dest, src, n) << std::endl;
Other than that, it's still not... |
3,431,704 | 3,431,787 | Use different sets of functions based on template parameters (C++ traits?) | I have defined a class in C++ which holds an array of scalars of type T for which I want to define operators like sin, cos, etc. For defining the meaning of sin applied on an object of this class I need to know the meaning of sin applied on the single scalar type T. This means I need to use appropriate math libraries (... | Isn't argument-dependent look-up good enough?
#include <cmath>
#include <iostream>
namespace xxx {
class X
{
};
X sin(X) { return X(); }
} //xxx
std::ostream& operator<< (std::ostream& os, xxx::X)
{
return os << "X";
}
template <class T>
void use_sin(T t)
{
using std::sin; //primitive types are not in a nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.