Rectangle 27 3

Related posts

I've seen many posts about memory allocation in C++, questions about "new operator" vs "operator new", questions about new int(100) vs new int[100], questions about memory initialization... I think there should be an answer that summarizes everything clearly once and for all, and I'm choosing this question to write this summary. It is about dynamic memory allocation, ie allocations on the heap at runtime. I also provide a summary implementation (public domain).

Main functions for dynamic memory allocations:

  • In C (header <cstdlib>), we have mainly malloc and calloc and free. I won't talk about realloc.
<new>
new T( args )
new (std::nothrow) T( args )
delete ( T* )
new T[ size_t ]
new (std::nothrow) T[ size_t ]
delete[] ( T* )
new (void*) T( args )
new (void*) T[ size_t ]
::operator new( size_t, ptr )

Main points: complete type-erasure (void* pointers), and therefore no construction/destruction, size specified in bytes (typically using sizeof).

malloc( size_t )
calloc( size_t, size_t )
free

Main points: confusing because of similar syntaxes doing different things, all delete-statements call the destructor, all delete-statements take fully typed pointers, some new-statements return fully-typed pointers, some new-statements call some constructor.

Warning: as you will see below, new can either be a keyword OR function. It is best not to talk about "new operator" and/or "operator new" in order to avoid confusions. I call "new-statements" any valid statements that contain new either as a function or keyword. People also talk about "new-expressions", where new is the keyword and not the function.

::operator new( size_t )
::operator new( size_t, std::nothrow )
void*
  • In case of failure, the former throws an exception std::bad_alloc, the latter returns NULL.
  • Use ::operator new( sizeof(T) ) for a single object of type T (and delete for release), and ::operator new( n*sizeof(T) ) for multiple objects (and delete[] for release).

These allocations do not initialize memory, and in particular, they do not call the default-constructor on the allocated objects. Therefore you MUST initialize ALL the elements manually before you release the allocation using either delete or delete[].

Note: I couldn't stress enough that you should NOT use this yourself. If you should use it, however, make sure you pass a pointer to void instead of a typed pointer when calling either delete or delete[] on such allocations (always after initializing manually). I have personally experienced runtime errors with non-POD types with some compilers (maybe my mistake).

Do not use this yourself.

void *ptr = ::operator new( n*sizeof(T) )

Then ::operator new( n*sizeof(T), (T*) ptr ) initializes n elements of type T starting from ptr using the default constructor T::T(). There is no allocation here, only initialization using the default-constructor.

  • new T( args ) allocates and initializes memory for a single object of type T using the constructor T::T( args ). The default constructor will not be called unless arguments are omitted (ie new T() or even new T). Throws an exception std::bad_alloc on failure.
  • Same for new (std::nothrow) T( args ) except that it returns NULL in case of failure.
  • Use delete to call the destructor T::~T() and release the corresponding memory.
  • new T[n] allocates and initializes memory for a n objects of type T using the default constructor. Throws an exception std::bad_alloc on failure.
  • Idem for new (std::nothrow) T[n] except that it returns NULL in case of failure.
  • Use delete[] to call the destructor T::~T() for each element and release the corresponding memory.

No allocation here. Regardless of how the allocation was made:

  • new (ptr) T(args) calls the constructor T::T(args) on the memory stored at ptr. The default constructor is not called unless arguments are omitted.
  • new (ptr) T[n] calls the default constructor T::T() on n objects of type T stored from ptr to ptr+n (ie, n*sizeof(T) bytes).
  • New operator vs operator new, avoid the confusion by not using these terms

What is Dynamic Memory Allocation in C++? - Stack Overflow

c++ memory-management malloc new-operator dynamic-allocation
Rectangle 27 3

Related posts

I've seen many posts about memory allocation in C++, questions about "new operator" vs "operator new", questions about new int(100) vs new int[100], questions about memory initialization... I think there should be an answer that summarizes everything clearly once and for all, and I'm choosing this question to write this summary. It is about dynamic memory allocation, ie allocations on the heap at runtime. I also provide a summary implementation (public domain).

Main functions for dynamic memory allocations:

  • In C (header <cstdlib>), we have mainly malloc and calloc and free. I won't talk about realloc.
<new>
new T( args )
new (std::nothrow) T( args )
delete ( T* )
new T[ size_t ]
new (std::nothrow) T[ size_t ]
delete[] ( T* )
new (void*) T( args )
new (void*) T[ size_t ]
::operator new( size_t, ptr )

Main points: complete type-erasure (void* pointers), and therefore no construction/destruction, size specified in bytes (typically using sizeof).

malloc( size_t )
calloc( size_t, size_t )
free

Main points: confusing because of similar syntaxes doing different things, all delete-statements call the destructor, all delete-statements take fully typed pointers, some new-statements return fully-typed pointers, some new-statements call some constructor.

Warning: as you will see below, new can either be a keyword OR function. It is best not to talk about "new operator" and/or "operator new" in order to avoid confusions. I call "new-statements" any valid statements that contain new either as a function or keyword. People also talk about "new-expressions", where new is the keyword and not the function.

::operator new( size_t )
::operator new( size_t, std::nothrow )
void*
  • In case of failure, the former throws an exception std::bad_alloc, the latter returns NULL.
  • Use ::operator new( sizeof(T) ) for a single object of type T (and delete for release), and ::operator new( n*sizeof(T) ) for multiple objects (and delete[] for release).

These allocations do not initialize memory, and in particular, they do not call the default-constructor on the allocated objects. Therefore you MUST initialize ALL the elements manually before you release the allocation using either delete or delete[].

Note: I couldn't stress enough that you should NOT use this yourself. If you should use it, however, make sure you pass a pointer to void instead of a typed pointer when calling either delete or delete[] on such allocations (always after initializing manually). I have personally experienced runtime errors with non-POD types with some compilers (maybe my mistake).

Do not use this yourself.

void *ptr = ::operator new( n*sizeof(T) )

Then ::operator new( n*sizeof(T), (T*) ptr ) initializes n elements of type T starting from ptr using the default constructor T::T(). There is no allocation here, only initialization using the default-constructor.

  • new T( args ) allocates and initializes memory for a single object of type T using the constructor T::T( args ). The default constructor will not be called unless arguments are omitted (ie new T() or even new T). Throws an exception std::bad_alloc on failure.
  • Same for new (std::nothrow) T( args ) except that it returns NULL in case of failure.
  • Use delete to call the destructor T::~T() and release the corresponding memory.
  • new T[n] allocates and initializes memory for a n objects of type T using the default constructor. Throws an exception std::bad_alloc on failure.
  • Idem for new (std::nothrow) T[n] except that it returns NULL in case of failure.
  • Use delete[] to call the destructor T::~T() for each element and release the corresponding memory.

No allocation here. Regardless of how the allocation was made:

  • new (ptr) T(args) calls the constructor T::T(args) on the memory stored at ptr. The default constructor is not called unless arguments are omitted.
  • new (ptr) T[n] calls the default constructor T::T() on n objects of type T stored from ptr to ptr+n (ie, n*sizeof(T) bytes).
  • New operator vs operator new, avoid the confusion by not using these terms

What is Dynamic Memory Allocation in C++? - Stack Overflow

c++ memory-management malloc new-operator dynamic-allocation
Rectangle 27 9

Related posts and questions

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong.

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 949
Date: Tue, 04 Jun 2013 02:59:35 GMT

This implies that the REST API does not exist in the URL you have provide.

  • You might have a typo in your request (believe me this can happen)!
  • It could be that your spring configuration is not right. If this is the case it needs further digging into what has actually gone wrong but I have provided some initial actions you need to do before start your more sophisticated investigation.

After you have made sure that everything is done perfectly right and nothing is wrong with your Configuration nor you URL: - Run a maven clean. - Undeploy your web app or simply delete it. - Redeploy the web app - Make sure to use only one version of Spring in your maven/gradle

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 968
Date: Tue, 04 Jun 2013 03:08:05 GMT
Connection: close

The only reason behind this is that fact that your request is not formatted correctly. If you checkout the detailed curl response you should be able to see "The request sent by the client was syntactically incorrect.".

Either your JSON format is not right or you are missing a mandatory parameter for the JAVA object.

Make sure you provide the JSON object in correct format and with the right number of parameters. Nullable properties are not mandatory but you do have to provide data for all NotNullable properties. It is VERY important to remember that Spring is using Java reflection to turn yours JSON file into Java objects, what does this mean? it means that variable and method names are CasE SensItiVe. If your JSON file is sending the variable "userName", than your matching variable in your Java object MUST also be named "userName". If you have getters and setters, they also have to follow the same rule. getUserName and setUserName to match our previous example.

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The Json media type is not supported by your web service. This could be due to your annotation not specifying the media type or you not specifying the media type in Curl post command.

Check your message convertor is set up correctly and make sure the web service annotation matches the example above. If these were fine, make sure you specify the content-type in your Curl post request.

The json media type is not supported by your web service.

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Content-Type: application/json;charset=UTF-8 
Transfer-Encoding: chunked 
Date: Tue, 04 Jun 2013 03:06:16 GMT

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how ...

java json spring curl html-post
Rectangle 27 9

Related posts and questions

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong.

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 949
Date: Tue, 04 Jun 2013 02:59:35 GMT

This implies that the REST API does not exist in the URL you have provide.

  • You might have a typo in your request (believe me this can happen)!
  • It could be that your spring configuration is not right. If this is the case it needs further digging into what has actually gone wrong but I have provided some initial actions you need to do before start your more sophisticated investigation.

After you have made sure that everything is done perfectly right and nothing is wrong with your Configuration nor you URL: - Run a maven clean. - Undeploy your web app or simply delete it. - Redeploy the web app - Make sure to use only one version of Spring in your maven/gradle

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 968
Date: Tue, 04 Jun 2013 03:08:05 GMT
Connection: close

The only reason behind this is that fact that your request is not formatted correctly. If you checkout the detailed curl response you should be able to see "The request sent by the client was syntactically incorrect.".

Either your JSON format is not right or you are missing a mandatory parameter for the JAVA object.

Make sure you provide the JSON object in correct format and with the right number of parameters. Nullable properties are not mandatory but you do have to provide data for all NotNullable properties. It is VERY important to remember that Spring is using Java reflection to turn yours JSON file into Java objects, what does this mean? it means that variable and method names are CasE SensItiVe. If your JSON file is sending the variable "userName", than your matching variable in your Java object MUST also be named "userName". If you have getters and setters, they also have to follow the same rule. getUserName and setUserName to match our previous example.

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The Json media type is not supported by your web service. This could be due to your annotation not specifying the media type or you not specifying the media type in Curl post command.

Check your message convertor is set up correctly and make sure the web service annotation matches the example above. If these were fine, make sure you specify the content-type in your Curl post request.

The json media type is not supported by your web service.

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Content-Type: application/json;charset=UTF-8 
Transfer-Encoding: chunked 
Date: Tue, 04 Jun 2013 03:06:16 GMT

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

java - Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how ...

java json spring curl html-post
Rectangle 27 76

CurrentValues.SetValues only updates scalar properties but no related entities, so you must do the same for each related entity:

If the relationship could have been removed altogether or have been created you also need to handle those cases explicitly:

You eventually also need to set the state of the attached entities to Modified if the relationship has been changed and the scalar properties as well.

If - according to your comment - Foo.SubFoo is actually a collection and not only a reference you will need something like this to update the related entities:

public Foo Edit(Foo newFoo)
{
    var dbFoo = context.Foo
                       .Include(x => x.SubFoo)
                       .Include(x => x.AnotherSubFoo)
                       .Single(c => c.Id == newFoo.Id);

    // Update foo (works only for scalar properties)
    context.Entry(dbFoo).CurrentValues.SetValues(newFoo);

    // Delete subFoos from database that are not in the newFoo.SubFoo collection
    foreach (var dbSubFoo in dbFoo.SubFoo.ToList())
        if (!newFoo.SubFoo.Any(s => s.Id == dbSubFoo.Id))
            context.SubFoos.Remove(dbSubFoo);

    foreach (var newSubFoo in newFoo.SubFoo)
    {
        var dbSubFoo = dbFoo.SubFoo.SingleOrDefault(s => s.Id == newSubFoo.Id);
        if (dbSubFoo != null)
            // Update subFoos that are in the newFoo.SubFoo collection
            context.Entry(dbSubFoo).CurrentValues.SetValues(newSubFoo);
        else
            // Insert subFoos into the database that are not
            // in the dbFoo.subFoo collection
            dbFoo.SubFoo.Add(newSubFoo);
    }

    // and the same for AnotherSubFoo...

    db.SaveChanges();

    return newFoo;
}

I don't get why EF is such an overkill for a similar situation. There must be an easier way of doing such an update.

When I implement this I got an error like that; "The property 'Id' is part of the object's key information and cannot be modified."

In Edit section we need to add one more condition of checking if id == 0 something like if (dbSubFoo != null && dbSubFoo.ID != 0) because if you have 5 new items then all will have id as 0 and once we add 1st one all later will be treated as existing because it will found item with id 0 as existing

c# - Entity framework, problems updating related objects - Stack Overf...

c# entity-framework ef-code-first
Rectangle 27 2831

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string, object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

string
string' is a keyword in c#, so you can not use it as a variable  name.For Ex:
//compiler error, but
String

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

.net - What is the difference between String and string in C#? - Stack...

c# .net string types
Rectangle 27 2769

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string, object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

string
string' is a keyword in c#, so you can not use it as a variable  name.For Ex:
//compiler error, but
String

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

.net - What is the difference between String and string in C#? - Stack...

c# .net string types
Rectangle 27 15

For disabling all the database related autoconfiguration and exit from:

@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(PayPalApplication.class, args);
    }
}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

hibernate - Disable all Database related auto configuration in Spring ...

spring hibernate spring-boot spring-data spring-data-jpa
Rectangle 27 2764

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string, object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

string
string' is a keyword in c#, so you can not use it as a variable  name.For Ex:
//compiler error, but
String

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

.net - What is the difference between String and string in C#? - Stack...

c# .net string types
Rectangle 27 2764

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string, object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

string
string' is a keyword in c#, so you can not use it as a variable  name.For Ex:
//compiler error, but
String

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

.net - What is the difference between String and string in C#? - Stack...

c# .net string types
Rectangle 27 2759

Just for the sake of completeness, here's a brain dump of related information...

As others have noted, string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

Apart from string, object, the aliases are all to value types. decimal is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr.

In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime literals, and has an alias for it too.)

There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:

public enum Foo : UInt32 {} // Invalid
public enum Bar : uint   {} // Valid

That's just a matter of the way the spec defines enum declarations - the part after the colon has to be the integral-type production, which is one token of sbyte, byte, short, ushort, int, uint, long, ulong, char... as opposed to a type production as used by variable declarations for example. It doesn't indicate any other difference.

Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called ReadInt32 is unambiguous, whereas a method called ReadInt requires interpretation. The caller could be using a language which defines an int alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.

The inheritance situation with enum is interesting. Can you point to documentation onto why alias must be used for enumerations? Or is this a known bug?

It's in section 14.1 of the spec (I can't quote here easily as it's too long). It doesn't explicitly say that you've got to use the alias, but the aliases are sort of treated as their own types. It's all a bit weird.

@PiPeep what's more astounding than the large amount of upvotes is the staggering low amount of downvotes (consider the top 5 posts have a total of over 2000 upvotes, and yet only 1 downvote amongst them all). Especially when you factor in the notion that there's always "haters" in any community, I really find that simply incredible.

string
string' is a keyword in c#, so you can not use it as a variable  name.For Ex:
//compiler error, but
String

@SanjeevRai: Yes. You can use @string to create an identifier which ends up as string though. It's a sort of escaping mechanism.

.net - What is the difference between String and string in C#? - Stack...

c# .net string types
Rectangle 27 27

Not what you're after but related:

def index
  @regions = Region.all
  respond_to do |format|
    format.json { render :json => @regions }
    format.any(:xml, :html) { render :xml => @regions }
  end
end

Rails 3 respond_to: default format? - Stack Overflow

ruby-on-rails ruby-on-rails-3
Rectangle 27 824

The difference is caused by the same super-alignment issue from the following related questions:

But that's only because there's one other problem with the code.

Starting from the original loop:

for(i=1;i<SIZE-1;i++) 
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        for(k=-1;k<2;k++) 
            for(l=-1;l<2;l++) 
                res[j][i] += img[j+l][i+k];
        res[j][i] /= 9;
}

First notice that the two inner loops are trivial. They can be unrolled as follows:

for(i=1;i<SIZE-1;i++) {
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

So that leaves the two outer-loops that we're interested in.

You are iterating the matrix column-wise instead of row-wise.

To solve this problem, you should interchange the two loops.

for(j=1;j<SIZE-1;j++) {
    for(i=1;i<SIZE-1;i++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.

8191: 1.499 seconds
8192: 2.122 seconds
8193: 1.582 seconds
8191: 0.376 seconds
8192: 0.357 seconds
8193: 0.351 seconds

I'll also note that unrolling the inner loops has no effect on performance. The compiler probably does it automatically. I unrolled them for the sole purpose of getting rid of them to make it easier to spot the problem with the outer loops.

And you can speed this code up by another factor of three by caching the sums along each row. But that and other optimizations are outside the scope of the original question.

@ClickUpvote This is actually a hardware (caching) issue. It has nothing to do with the language. If you tried it in any other language that compiles or JITs to native code, you would probably see the same effects.

@ClickUpvote: You seem rather misguided. That "second loop" was just Mystical unrolling the inner loops by hand. This is something your compiler will almost certainly do anyway, and Mystical only did it to make the issue with the outer loops more obvious. It is by no means something you should bother doing yourself.

THIS is a perfect example of a good answer on SO: References similar questions, explains step-by-step how you approached it, explains the problem, explains how to FIX the problem, has great formatting, and even an example of the code running on your machine. Thank you for your contribution.

c++ - Why is my program slow when looping over exactly 8192 elements? ...

c++ performance memory-management gcc
Rectangle 27 824

The difference is caused by the same super-alignment issue from the following related questions:

But that's only because there's one other problem with the code.

Starting from the original loop:

for(i=1;i<SIZE-1;i++) 
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        for(k=-1;k<2;k++) 
            for(l=-1;l<2;l++) 
                res[j][i] += img[j+l][i+k];
        res[j][i] /= 9;
}

First notice that the two inner loops are trivial. They can be unrolled as follows:

for(i=1;i<SIZE-1;i++) {
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

So that leaves the two outer-loops that we're interested in.

You are iterating the matrix column-wise instead of row-wise.

To solve this problem, you should interchange the two loops.

for(j=1;j<SIZE-1;j++) {
    for(i=1;i<SIZE-1;i++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.

8191: 1.499 seconds
8192: 2.122 seconds
8193: 1.582 seconds
8191: 0.376 seconds
8192: 0.357 seconds
8193: 0.351 seconds

I'll also note that unrolling the inner loops has no effect on performance. The compiler probably does it automatically. I unrolled them for the sole purpose of getting rid of them to make it easier to spot the problem with the outer loops.

And you can speed this code up by another factor of three by caching the sums along each row. But that and other optimizations are outside the scope of the original question.

@ClickUpvote This is actually a hardware (caching) issue. It has nothing to do with the language. If you tried it in any other language that compiles or JITs to native code, you would probably see the same effects.

@ClickUpvote: You seem rather misguided. That "second loop" was just Mystical unrolling the inner loops by hand. This is something your compiler will almost certainly do anyway, and Mystical only did it to make the issue with the outer loops more obvious. It is by no means something you should bother doing yourself.

THIS is a perfect example of a good answer on SO: References similar questions, explains step-by-step how you approached it, explains the problem, explains how to FIX the problem, has great formatting, and even an example of the code running on your machine. Thank you for your contribution.

c++ - Why is my program slow when looping over exactly 8192 elements? ...

c++ performance memory-management gcc
Rectangle 27 823

The difference is caused by the same super-alignment issue from the following related questions:

But that's only because there's one other problem with the code.

Starting from the original loop:

for(i=1;i<SIZE-1;i++) 
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        for(k=-1;k<2;k++) 
            for(l=-1;l<2;l++) 
                res[j][i] += img[j+l][i+k];
        res[j][i] /= 9;
}

First notice that the two inner loops are trivial. They can be unrolled as follows:

for(i=1;i<SIZE-1;i++) {
    for(j=1;j<SIZE-1;j++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

So that leaves the two outer-loops that we're interested in.

You are iterating the matrix column-wise instead of row-wise.

To solve this problem, you should interchange the two loops.

for(j=1;j<SIZE-1;j++) {
    for(i=1;i<SIZE-1;i++) {
        res[j][i]=0;
        res[j][i] += img[j-1][i-1];
        res[j][i] += img[j  ][i-1];
        res[j][i] += img[j+1][i-1];
        res[j][i] += img[j-1][i  ];
        res[j][i] += img[j  ][i  ];
        res[j][i] += img[j+1][i  ];
        res[j][i] += img[j-1][i+1];
        res[j][i] += img[j  ][i+1];
        res[j][i] += img[j+1][i+1];
        res[j][i] /= 9;
    }
}

This eliminates all the non-sequential access completely so you no longer get random slow-downs on large powers-of-two.

8191: 1.499 seconds
8192: 2.122 seconds
8193: 1.582 seconds
8191: 0.376 seconds
8192: 0.357 seconds
8193: 0.351 seconds

I'll also note that unrolling the inner loops has no effect on performance. The compiler probably does it automatically. I unrolled them for the sole purpose of getting rid of them to make it easier to spot the problem with the outer loops.

And you can speed this code up by another factor of three by caching the sums along each row. But that and other optimizations are outside the scope of the original question.

@ClickUpvote This is actually a hardware (caching) issue. It has nothing to do with the language. If you tried it in any other language that compiles or JITs to native code, you would probably see the same effects.

@ClickUpvote: You seem rather misguided. That "second loop" was just Mystical unrolling the inner loops by hand. This is something your compiler will almost certainly do anyway, and Mystical only did it to make the issue with the outer loops more obvious. It is by no means something you should bother doing yourself.

THIS is a perfect example of a good answer on SO: References similar questions, explains step-by-step how you approached it, explains the problem, explains how to FIX the problem, has great formatting, and even an example of the code running on your machine. Thank you for your contribution.

c++ - Why is my program slow when looping over exactly 8192 elements? ...

c++ performance memory-management gcc
Rectangle 27 15

See here for a related question:

in which a great article on margin collapse is presented:

The answer is that the margin on H1 collapses with its parent(.content-area) margin (0 in this case), and so the parent div takes on the H1 margin. To prevent that, the parent div (.content-area) needs to have a padding set or a border or something set to prevent the collapse (which, in my case, brings my two divs together correctly)

+1, very nice. To re-iterate this answer, just set a padding-top on #content-area

html - css vertical gap between divs - Stack Overflow

html css
Rectangle 27 15

Workspaces and repositories shouldn't be related.

The workspace is really just where Eclipse stores a bunch of settings. Project files can (and usually do) live in the workspace, but as you know, they can be imported from an external source--the import is just a logical link.

You can create as many workspaces as you want for specific purposes; you could even import projects in one workspace into another if you had reason to do so.

The SVN layout should be separate from how your workspace is defined. They may end up looking similar, but that shouldn't imply that they're actually the same. I'd recommend each Eclipse project have its own SVN project, so that instead of having

you have

What this does for you is give you the flexibility to lay out your workspace completely separate from how your repository is structured. You'll be able to check out individual projects into the workspace without having to checkout the entire codebase. You'll be able to have projects checked out on development branches while others are on the trunk, you can revert changes to one project while leaving another alone and so forth.

The last question about which artifacts to check into SVN is a matter of taste. I'd recommend checking in whatever artifacts are universal across the development team. If Eclipse is the standard IDE, go ahead and check in the .project and .classpath files so that a new developer will be able to checkout and build immediately. If certain plugins are universal and have config files of their own, go ahead and check those in as well. On the other hand, anything that isn't shared across the dev team should be left out of the repository.

Further experience has taught me that the only things that should go into source control are the actual source files. Configuration and setup files should be regenerated by the developer when setting up a new project.

We use the same approach at my company, and it's proven suboptimal; you have separate branches for each of your projects, which makes handling different release branches very cumbersome (i.e. you have to load project A for release X and project B for the same release separatly).

I'll agree that it's not as simple as having every Eclipse project under a single svn project, but it's far more flexible.

Flexibility comes at a price; my experience with this naming scheme leads me to believe that the cost in manual work and potential for mistakes simply isn't worth the trouble. Since SVN only actually copies files on-demand, I prefer to branch out my entire workspace rather than individual projects.

Fair enough; I can see advantages and disadvantages to both methods so it might just be a matter of personal preference.

How to layout folders locally and in SVN when using eclipse - Stack Ov...

eclipse svn
Rectangle 27 4

While saving an item in Page Editor, Sitecore saves all the field renderers which are displayed on the page, so if you set the Item property of a FieldRenderer1 to "Product Example Test" Sitecore Item, Page Editor know which item should be saved.

The problem with publishing is that you enqueue the current item in the publishing queue, but this item has no link to the "Product Example Test" Sitecore Item in any of its properties cause you're setting the Item property of the field renderer dynamically in the code.

Page Editor
Edit Related Item
Publish Related Item

Sitecore Page Editor Publishing items related to content - Stack Overf...

sitecore page-editor
Rectangle 27 73

The two patterns are certainly related!

The difference between patterns is generally in intent.

The intent of Factory Method is "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

The intent of Abstract Factory is "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Based purely on these intent statements (quoted from GoF), I would say that indeed Factory Method is in some sense a "degenerate" Abstract Factory with a family of one.

They generally tend to differ in implementation, as Factory Method is a good deal simpler than Abstract Factory.

They are related also in implementation however. As noted in the GoF book,

I understand neither the comment nor the downvote. Can you elaborate?

language agnostic - Design Patterns: Abstract Factory vs Factory Metho...

design-patterns language-agnostic uml factory-method abstract-factory
Rectangle 27 73

The two patterns are certainly related!

The difference between patterns is generally in intent.

The intent of Factory Method is "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

The intent of Abstract Factory is "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

Based purely on these intent statements (quoted from GoF), I would say that indeed Factory Method is in some sense a "degenerate" Abstract Factory with a family of one.

They generally tend to differ in implementation, as Factory Method is a good deal simpler than Abstract Factory.

They are related also in implementation however. As noted in the GoF book,

I understand neither the comment nor the downvote. Can you elaborate?

language agnostic - Design Patterns: Abstract Factory vs Factory Metho...

design-patterns language-agnostic uml factory-method abstract-factory