Initialisation and assignment

后端 未结 6 2120
不思量自难忘°
不思量自难忘° 2020-11-29 04:16

What EXACTLY is the difference between INITIALIZATION and ASSIGNMENT ?

PS : If possible please give examples in C and C++ , specifically .

Actually , I was

相关标签:
6条回答
  • 2020-11-29 04:30

    One thing that nobody has yet mentioned is the difference between initialisation and assignment of class fields in the constructor.

    Let us consider the class:

    class Thing
    {
      int num;
      char c;
    public:
      Thing();
    };
    
    Thing::Thing()
      : num(5)
    {
      c = 'a';
    }
    

    What we have here is a constructor that initialises Thing::num to the value of 5, and assigns 'a' to Thing::c. In this case the difference is minor, but as was said before if you were to substitute int and char in this example for some arbitrary classes, we would be talking about the difference between calling a parameterised constructor versus a default constructor followed by operator= function.

    0 讨论(0)
  • 2020-11-29 04:36

    Oh my. Initialization and assignment. Well, that's confusion for sure!

    To initialize is to make ready for use. And when we're talking about a variable, that means giving the variable a first, useful value. And one way to do that is by using an assignment.

    So it's pretty subtle: assignment is one way to do initialization.

    Assignment works well for initializing e.g. an int, but it doesn't work well for initializing e.g. a std::string. Why? Because the std::string object contains at least one pointer to dynamically allocated memory, and

    • if the object has not yet been initialized, that pointer needs to be set to point at a properly allocated buffer (block of memory to hold the string contents), but

    • if the object has already been initialized, then an assignment may have to deallocate the old buffer and allocate a new one.

    So the std::string object's assignment operator evidently has to behave in two different ways, depending on whether the object has already been initialized or not!

    Of course it doesn't behave in two different ways. Instead, for a std::string object the initialization is taken care of by a constructor. You can say that a constructor's job is to take the area of memory that will represent the object, and change the arbitrary bits there to something suitable for the object type, something that represents a valid object state.

    That initialization from raw memory should ideally be done once for each object, before any other operations on the object.

    And the C++ rules effectively guarantee that. At least as long as you don't use very low level facilities. One might call that the C++ construction guarantee.

    So, this means that when you do

        std::string s( "one" );
    

    then you're doing simple construction from raw memory, but when you do

        std::string s;
        s = "two";
    

    then you're first constructing s (with an object state representing an empty string), and then assigning to this already initialized s.

    And that, finally, allows me to answer your question. From the point of view of language independent programming the first useful value is presumably the one that's assigned, and so in this view one thinks of the assignment as initialization. Yet, at the C++ technical level initialization has already been done, by a call of std::string's default constructor, so at this level one thinks of the declaration as initialization, and the assignment as just a later change of value.

    So, especially the term "initialization" depends on the context!

    Simply apply some common sense to sort out what Someone Else probably means.

    Cheers & hth.,

    0 讨论(0)
  • 2020-11-29 04:39

    Initialisation: giving an object an initial value:

    int a(0);
    int b = 2;
    int c = a;
    int d(c);
    std::vector<int> e;
    

    Assignment: assigning a new value to an object:

    a = b;
    b = 5;
    c = a;
    d = 2;
    
    0 讨论(0)
  • 2020-11-29 04:46

    In the simplest of terms:

    int a = 0;  // initialization of a to 0
    a = 1;      // assignment of a to 1
    

    For built in types its relatively straight forward. For user defined types it can get more complex. Have a look at this article.

    For instance:

    class A
    {
    public:
       A() : val_(0)  // initializer list, initializes val_
       {}
    
       A(const int v) : val_(v) // initializes val_
       {}
    
       A(const A& rhs) : val_(rhs.val_)  // still initialization of val_
       {}
    
    private:
        int val_;
    };
    
    // all initialization:
    A a;
    A a2(4);
    A a3(a2);
    
    a = a3; // assignment
    
    0 讨论(0)
  • 2020-11-29 04:51

    Initialization is creating an instance(of type) with certain value.

    int i = 0;
    

    Assignment is to give value to an already created instance(of type).

    int i;
    i = 0
    

    To Answer your edited Question:

    What is the difference between Initializing And Assignment inside constructor? &
    What is the advantage?

    There is a difference between Initializing a member using initializer list and assigning it an value inside the constructor body.

    When you initialize fields via initializer list the constructors will be called once.

    If you use the assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

    As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

    For an integer data type or POD class members there is no practical overhead.


    An Code Example:

    class Myclass
    {
    public: 
     Myclass (unsigned int param) : param_ (param)
     {
     }
    
    unsigned int param () const
    {
         return param_;
    }
    
    private:
         unsigned int param_;
    };
    

    In the above example:

    Myclass (unsigned int param) : param_ (param)
    

    This construct is called a Member Initializer List in C++.

    It initializes a member param_ to a value param.


    When do you HAVE TO use member Initializer list?
    You will have(rather forced) to use a Member Initializer list if:

    Your class has a reference member
    Your class has a const member or
    Your class doesn't have a default constructor

    0 讨论(0)
  • In C the general syntax for initialization is with {}:

    struct toto { unsigned a; double c[2] };
    struct toto T = { 3, { 4.5, 3.1 } };
    struct toto S = { .c = { [1] = 7.0 }, .a = 32 };
    

    The one for S is called "designated initializers" and is only available from C99 onward.

    • Fields that are omitted are automatically initialized with the correct 0 for the corresponding type.
    • this syntax applies even to basic data types like double r = { 1.0 };
    • There is a catchall initializer that sets all fields to 0, namely { 0 }.
    • if the variable is of static linkage all expressions of the initializer must be constant expressions

    This {} syntax can not be used directly for assignment, but in C99 you can use compound literals instead like

     S = (struct toto){ .c = { [1] = 5.0 } };
    

    So by first creating a temporary object on the RHS and assigning this to your object.

    0 讨论(0)
提交回复
热议问题